eof() bad practice? [duplicate]

You can use eof to test for the exact condition it reports – whether you have attempted to read past end of file. You cannot use it to test whether there’s more input to read, or whether reading succeeded, which are more common tests.

Wrong:

while (!cin.eof()) {
  cin >> foo;
}

Correct:

if (!(cin >> foo)) {
  if (cin.eof()) {
    cout << "read failed due to EOF\n";
  } else {
    cout << "read failed due to something other than EOF\n";
  }
}

Leave a Comment