I am looking at how to read lines from a file. I already know how to do this since I am looking at a correct example of this. But I want to know how it works in detail.
I know that it should never print the first lines of the file, since I simply overwrite them until it reaches EOF. However, why does it not print the last line? Because when the last line is read and stored in the string, the while loop is broken and it should be printed. How does this exactly work in detail?
What am I missing?
Your example should work, except you're only printing the last line of the file. (And most files end with a newline.) getline strips the newline character--which is why the endl is added to the output to make it look right.
I usually do this:
1 2 3 4 5 6
fstream fin( "file.txt" );
string line;
while( getline( fin, line ) ) {
// process line, for example:
cout << line << endl;
}
Let's say the the file has two lines: "Line 1" and "Line2".
It looks like this. Line 1\nLine2\nEOF.
Is it possible that the following happens at the end:
First loop, it reads "Line 1" and discards the first '\n'.
Second loop, it reads "Line 2" and discards the second '\n'.
But inFile has yet not hit EOF, it only discarded the '\n' before it.
So therefore it runs a 3:rd time and since there is only the EOF left,
nothing is read and the program terminates.
There is a difference in behaviour depending on whether the last line does or does not end with a newline character.
But in any case, using the value of a variable after an unsuccessful input operation is not a good idea. For reliable results, make use of the value only when the read was successful. Example: