Search code examples
c++validationinputstl

Resetting cin stream state C++


Here Im trying to get an integer from user, looping while the input is correct.

After entering non integer value (e.g "dsdfgsdg") cin.fail() returns true, as expected and while loop body starts executing.

Here I reset error flags of cin, using cin.clear(); and cin.fail() returns false, as expected.

But next call to cin doesn't work and sets error flags back on.

Any ideas?

#include<iostream>
using namespace std;

int main() {
  int a;
  cin >> a;

  while (cin.fail()) {
    cout << "Incorrect data. Enter new integer:\n";
    cin.clear();
    cin >> a;
  }
} 

Solution

  • After cin.clear(), you do this:

    #include <iostream> //std::streamsize, std::cin
    #include <limits> //std::numeric_limits
    ....
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
    

    What the above does is that it discards any characters that are still left in the stream until EOF or until it has discarded the delimiter (\n in this case).

    Without doing this, cin >> a; will continue reading the same non-integer characters and your program will keep looping.