How to clear cin Buffer in c++

删除回忆录丶 提交于 2021-02-08 11:55:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!