Read all lines from a file.

Hi.

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.

For example, why doesn't this work?
1
2
3
4
5
6
std::string strInFile;
	while(inFile)
	{
		getline(inFile,strInFile);
	}
	std::cout << strInFile << std::endl;


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;
}


getline returns the stream so you can check it right in the while loop like that. For reference:
http://www.cplusplus.com/reference/string/string/getline/?kw=getline
Last edited on
I came to one conclusion that could be wrong:

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.

Is this right?
Just needed to bookmark this topic by posting.
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:
1
2
3
4
5
6
7
    std::string strInFile;
    std::string latestLine;
    while (getline(inFile, strInFile))
    {
        latestLine = strInFile;
    }
    std::cout << latestLine << std::endl;
Is this right?


Can you think of a way to find out? (Write a program that will prove/disprove the theory.)
Also note that with most current operating/file systems EOF is a state, not a value that you read.


Last edited on
Topic archived. No new replies allowed.