-2

For part of a C++ project I need to store all the words from a list in a .txt document into a string. The .txt document is formatted like this:

Word1 Word2 Word3 Word4

I can open the file with no problem, but I'm struggling to save all the words in the file to a string. Would someone be able to help me get started?

1 Answers1

1

I don't know what process are you using to get input from the file. So I am going to describe the easiest. freopen . To open a file using freopen you just type

freopen("a.txt","r",stdin);

at the begining of the main function. Every thing after this would be like you are taking input from console. Now about your string. I don't know if you want to save the words in a space separated string or not, I assume you want that. Here is an example code

string main_string;
string temporary_string; // word read in each attempt;
while(cin>>temporary_string)
{
   main_string = main_string +" "+temporary_string;

}

this code will read until the end of file. You can also use the append function

Tamim Addari
  • 6,271
  • 9
  • 37
  • 52
  • How exactly does freopen work? What do each parts of it do? – user3902638 Aug 02 '14 at 18:28
  • The first parameter is the path of the file you want to read text from, the second parameter is the mode the file will open , and the third is the FILE stream that is bounded. cin,scanf is the standard input , so after freopen when ever you will specify cin or scanf , the input will be taken from the file instead of console. – Tamim Addari Aug 02 '14 at 18:33
  • you can mark the ans as accepted – Tamim Addari Aug 02 '14 at 18:49