If you are instructed to use .eof() you should reconsider the quality of your instruction. Using EOF has
always been wrong.
The most correct (and simplest to understand, IMHO) way to look at it is:
1 2 3 4 5 6 7 8 9 10 11 12
|
while (true)
{
// try to get input
getline( cin, s );
// did the attempt fail?
// if so, break the loop
if (!cin) break;
// otherwise, all is good. play with your input
do_something( s );
}
|
C++ is designed to make that kind of thing really pretty, because getline() returns the argument stream, which can then be automagically tested for goodness in a while/for/if/whatever condition:
1 2 3 4 5
|
while (getline( cin, s ))
{
// If I get this far, then input was good
do_something( s );
}
|
When you loop on EOF, you process even the bad inputs, because the test for goodness only occurs at the beginning of each loop, instead of immediately after an attempt to obtain input like it should:
1 2 3 4 5 6 7 8 9 10
|
while (!f.eof()) // BAD! BAD! BAD! BAD! BAD!
{
// attempt to get input
getline( f, s );
// even if input was bad, here we go...
do_something( s );
// time to loop and test whether or last attempt at input was good
}
|
Likewise, testing for EOF has another pitfall: it only tests for EOF. If your input was bad in some
other way (say, you tried to read an int but the input was "ABC"), then you have just created an infinite loop, since .eof() will never return true.
Hope this helps.