3
while(true)
{

int a, c;
string b;

file >> a >> b >> c;
if( file.good() )
    f(a, b, c);`
else
    break;
}

This code is not reading the last line form .txt file. If I change file.good() to !file.fail() it works. Why?

edmz
  • 8,220
  • 2
  • 26
  • 45
redoranish
  • 39
  • 4
  • when you will have `eof`, `fail()` and `good()` will give you `false` both, see [here](http://en.cppreference.com/w/cpp/io/basic_ios/good) – grisha Jul 28 '15 at 20:20
  • @up how to read that table showing the value of basic_ios accessors? I can see now the difference between good() and fail() but not exactly in which cases. – redoranish Jul 28 '15 at 20:47

2 Answers2

3

bad() --> Returns true if a reading or writing operation fails. For example, in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left.

fail() --> Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number.

good() --> It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true. Note that good and bad are not exact opposites (good checks more state flags at once).

Will elaborate latter.

3

I think this is covered here.

A relevant excerpt: "All of the stream state functions – fail, bad, eof, and good – tell you the current state of the stream rather than predicting the success of a future operation. Check the stream itself (which is equivalent to an inverted fail check) after the desired operation"

Community
  • 1
  • 1
  • 1
    Another important thing to glean from the example linked here is the idiomatic way in which the input is read from a stream! Basically, it is easier to avoid this sort of problem if you are always checking the state of the stream before you read a given input, rather than after. – cowsock Jul 28 '15 at 20:35