问题
I have gone through many existing answers here StackOverflow, but I am still stuck.
code:
int c;
cin >> c;
if(cin.fail()) {
cout << "Wrong Input";
cin.clear();
cin.ignore(INT_MAX, '\n');
}
else
{
cout << c*2;
}
If I enter wring input e.g s
instead of an integer, it outputs Wrong Input
. However, if I enter an integer, and then I enter a string, it ignores the string and keep outputting the previous integer result, hence it does not clears the cin buffer, and the old value of c
keeps on executing.
Can anyone please suggest the best way other than cin.ignore()
as it does not seem to work.
and yeah for me, the max() in cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
gives error. So this does not work either.
回答1:
the max() function needs to be defined in the beginning of the file. cin.ignore()
works very well to clear the buffer, however you need the numeric limits function max(), which in my case was giving error.
Solution:
#ifdef max
#define max
#endif
add these lines on the top, and a function such as following will work fine.
int id;
bool b;
do {
cout << "Enter id: ";
cin >> id;
b = cin.fail();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while ( b == true);
P.S: Thanks @Nathan
来源:https://stackoverflow.com/questions/40003190/how-to-clear-cin-buffer-in-c