我有一个while循环,只是检查输入的数字是否为2。如果用户无意中输入了字母而不是数字,即使我添加了isdigit,循环也会变为无穷大,但并没有解决循环问题如果输入的字符是疯狂的。这是代码:
int num1;
bool cond {false};
while(!cond){
cout<<"enter 2:";
cin>>num1;
if (!isdigit(num1)){
cout<<"not a digit:";
cin>>num1;
}
//
if(num1 == 2)
cond = true;
}
我建议尝试一些更简单的方法,而不是您当前的代码:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int num1;
cout << "Please enter the number 2:";
cin >> num1;
while (num1 != 2)
{
cin.clear(); //Clears the error flag on cin.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You did not enter the number 2, Please try again:";
cin >> num1;
}
return 0;
}
现在,cin.ignore(numeric_limits<streamsize>::max(), '\n');
是何时忽略直到'\n'
或是EOF
\n
分隔符的含义,即分隔符cin
将停止忽略的字符。
此外,numeric_limits<streamsize>::max()
基本上是说对要忽略的字符数没有限制。
您需要使用头文件#include<limits>
来使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句