tags:

views:

49

answers:

3
while(getline(fileIn,line))
{

  fileOut <<line<<endl;


}





while(getline(fileIn,line))
{

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


}

i have tried both piece of code and it still reads past and does not break. can anyone tell me why?

I am just reading from file and writing to it.

thank

A: 

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);
Pestilence
eofbit rarely does what the user wants and enabling exceptions for it is generally a very bad idea. It is enough to enable failbit to have full error handling but I would not recommend this either if the program reads until the end, as that would cause an exception to be thrown in a non-exceptional (but instead excepted) situation.
Tronic
it was a typo i fixed it. but the problem remains.
djones2010
@Tronic good points
Pestilence
A: 

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

Tronic
+1  A: 

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.

Kristo