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;
}
}
As a matter of style, prefer this method:
cin.clear() does not clear the buffer; it resets the error flags. So you will still have the sting you entered in your buffer and the code will not allow you to enter new data until you clear the cin buffer.
cin.Ignore()
should do the trickAfter
cin.clear()
, you do this:What the above does is that it clears the input stream of any characters that are still left there. Otherwise cin will continue trying to read the same characters and failing