How to read lines correctly form text file?

Hi, I'm wanted to know what is the best and secure way to read lines from files.
Though my university books and teachers taught me to do it like this:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 ifstream someFile("file.txt");

/**
Some code....
**/
string line;
while(!someFile.eof()){

readline(someFile,line);

/**
Some more code...
*/
}




I read on many forums that it is a bad programing to put the eof() in the while loop. Instead I should put the readline(someFile,line) inside the while loop. Can some please explain to me why and what is the right way to do it?
Another what is the difference between good() and eof()? I've seen both and I guess they do the same thing
Last edited on
Hello Edward01,

Do not use the while condition of (!????.eof) as this will not behave the way you want. The readline is inside is inside the while loop. So any processing after the check will process a bad read before the while condition can check the state of the stream because (eof) is set after a failed read. What is more often done is this:

1
2
3
4
5
6
7
ifstream someFile("file.txt");
std::string str{""};

while (std::getline(someFile, str)
{
    // your code here
}


This way when you try to read past (eof) someFile will fail and the while loop will fail.

The only real difference between "good", "fail", "bad" and "eof" is which state bits they check. Whereas "good" will check all the state bits the others will only check one state bit.

I would say that it will depend on what you are trying to do as to which one to use. "eof" can work, but where you check for "eof" is important.

Hope that helps,

Andy
Topic archived. No new replies allowed.