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:
";
cin.clear();
cin >> a;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…