如何在C ++中清除cin缓冲区 [英] How to clear cin Buffer in c++

查看:126
本文介绍了如何在C ++中清除cin缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在StackOverflow上浏览了许多现有的答案,但是我仍然被困住.

代码:

  int c;cin>>C;if(cin.fail()){cout<<输入错误";cin.clear();cin.ignore(INT_MAX,'\ n');}别的{cout<<c * 2;} 

如果我输入拧输入(例如 s 而不是整数),则会输出 Wrong Input .但是,如果我输入一个整数,然后输入一个字符串,它将忽略该字符串并继续输出先前的整数结果,因此它不会清除cin缓冲区,并且 c 的旧值会保留在执行.除了 cin.ignore()之外,任何人都可以提出最好的建议,因为它似乎不起作用.对我来说, cin.ignore(std :: numeric_limits< std :: streamsize> :: max(),'\ n'); 中的max()给出了错误.因此,这也不起作用.

解决方案

需要在文件的开头定义max()函数. cin.ignore()可以很好地清除缓冲区,但是您需要数值限制函数max(),在我的情况下,该函数给出了错误.

解决方案:

  #ifdef max#define max#万一 

在顶部添加这些行,然后执行以下功能就可以了.

  int id;布尔b;做 {cout<<输入ID:";cin>>ID;b = cin.fail();cin.clear();cin.ignore(numeric_limits< streamsize> :: max(),'\ n');} while(b == true); 

P.S:谢谢@Nathan

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.

解决方案

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

这篇关于如何在C ++中清除cin缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆