Correct way to use cin.fail()

cin.fail() returns true if the last cin command failed, and false otherwise.

An example:

int main() {
  int i, j = 0;

  while (1) {
    i++;
    cin >> j;
    if (cin.fail()) return 0;
    cout << "Integer " << i << ": " << j << endl;  
  }
}

Now suppose you have a text file – input.txt and it’s contents are:

  30 40 50 60 70 -100 Fred 99 88 77 66

When you will run above short program on that, it will result like:

  Integer 1: 30
  Integer 2: 40
  Integer 3: 50
  Integer 4: 60
  Integer 5: 70
  Integer 6: -100

it will not continue after 6th value as it quits after reading the seventh word, because that is not an integer: cin.fail() returns true.

Leave a Comment