djones2010
djones2010

Reputation: 379

How to detect end-of-file when using getline?

while(getline(fileIn,line))
{

  fileOut <<line<<endl;

}


while(getline(fileIn,line))
{

  if(fileIn.eof())
   break;
  fileOut <<line<<endl;

}

I have tried both these pieces of code and the second one also reads past end-of-file and does not break. Can anyone tell me why?

I am just reading from a file and writing the lines out.

Upvotes: 1

Views: 5725

Answers (3)

Michael Kristofik
Michael Kristofik

Reputation: 35218

The getline function returns a reference to the stream you're reading. It evaluates to false if you try to read past EOF. The stream is still in a good state when you read the last line of the file. So you'll never reach the if-test in your second block of code.

Upvotes: 4

Tronic
Tronic

Reputation: 10430

The first code is correct and it certainly does end the loop after no data is left in the file.

Upvotes: 0

pestilence669
pestilence669

Reputation: 5699

Is that a comma between "fileIn" and "eof()"??? (second example)

One thing I like to do, is enable exceptions on my fstreams. YMMV:

ifstream file;
file.exceptions(ifstream::eofbit | ifstream::failbit | ifstream::badbit);

Upvotes: 0

Related Questions