Also using .eof could result in over-reading the file because the eof flag is not set until you actully hit the eof but using while(whateverinputmethod) will stop at the actual end of the file
This is what I thought the discussion was about, and I have not been able to discern how getline() will have a problem setting the eof error flag in the code I posted.
The reason I'd use getline in the condition instead of eof is the point joshdick is trying to make. If something happens and you cannot continue to read the file, the istream's fail bit is set. Only checking for eof could result in an infinite loop with faulty data since eof will never be set. It's helpful to stop reading the file as soon as an error occurs, and then you can check to see if the fail bit is set (which means an error occurred) or the eof bit (which means everything worked out).
Thank you for explaining this problem. I thought this might work instead:
Code:
while(myInputFile) //fails for any error flag?
{
getline(myInputFile, input);
cout<<"input: "<<input<<endl;
}
...but the eof error flag is not detected by that while condition, and therefore after the eof error flag has been set, the loop continues. Subsequently, another read attempt occurrs, but there is no more data, and a blank line is displayed as a result. When the additional read can't find any data, the failbit error flag is set causing the loop to end.
Apparently, the while loop condition:
while(myInputFile)
can only detect the failbit error flag or the badbit error flag--but not the eofbit error flag.
I used this code to confirm the eofbit error flag cannot end the loop:
Code:
while(myInputFile)
{
if(myInputFile.eof())
cout<<"eofbit error flag is set."<<endl;
getline(myInputFile, input);
cout<<"input: "<<input<<endl;
if(myInputFile.eof())
cout<<"eofbit error flag is set."<<endl;
if(myInputFile.bad())
cout<<"badbit error flag is set."<<endl;
if(myInputFile.fail())
cout<<"failbit error flag is set."<<endl;
}