I am working on a program that reads from a file and pushes back the contents of that file into a vector. It will read until the file reaches a space and push that string into a vector, then continue after the space. I have written this code.
ifstream inFile; inFile.open("message1.txt"); if (inFile.fail()) { cerr << "Could not find file" << endl; } while (inFile >> S) { code1.push_back(S); } I am just confused about the while (inFile >> S) actually does. I understand that it reads from the inFile until it reaches the end of file. But what does the inFile >> S condition actually do? Thanks for your time.
2 Answers
The expression inFile >> S reads a value into S and will return inFile.
This allows you to chain variables together like infile >> a >> b >> c;
Since this inFile is being used in a bool context, it will be converted to bool. And iostream objects are defined to convert to a bool that's true if and only if the object has no current error state.
What the inFile >> S does is take in the file stream, which is the data in you file, and uses a space delimiter (breaks it up by whitespace) and puts the contents in the variable S.
For example:
If we had a file that had the follow contents
the dog went running and we used inFile >> S with our file:
ifstream inFile("doginfo.txt") string words; while(inFile >> words) { cout << words << endl; } we will get the following output:
the dog went running The inFile >> S will continue to return true until there are no more items separated by whitespace.