C++ 检查整数。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18567483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Checking for an integer.
提问by xavi
New to C++. Having issues correctly looping while handling errors. I am trying to check if user input is an integer, and is positive.
C++ 新手。在处理错误时正确循环出现问题。我试图检查用户输入是否是整数,并且是正数。
do{
cout << "Please enter an integer.";
cin >> n;
if (cin.good())
{
if (n < 0) {cout << "Negative.";}
else {cout << "Positive.";}
}
else
{
cout << "Not an integer.";
cin.clear();
cin.ignore();
}
}while (!cin.good() || n < 0);
cout << "\ndone.";
When a non-integer is entered, the loop breaks. I feel like I am misunderstanding the inherent usage of cin.clear()
and cin.ignore()
and the status of cin
during this loop. If I remove the cin.ignore()
, the loop becomes infinite. Why is this? What can I do to make this into an elegantly functioning loop? Thank you.
当输入非整数时,循环中断。我觉得我在这个循环中误解了cin.clear()
andcin.ignore()
和 status的固有用法cin
。如果我删除cin.ignore()
,循环将变得无限。为什么是这样?我该怎么做才能使它成为一个优雅运行的循环?谢谢你。
采纳答案by Paul R
In your non-integer branch you are invoking further cin
methods so cin.good()
gets reset to true.
在您的非整数分支中,您正在调用更多cin
方法,因此cin.good()
被重置为 true。
You could change your code to something like this:
您可以将代码更改为如下所示:
while(1) { // <<< loop "forever"
cout << "Please enter an integer.";
cin >> n;
if (cin.good())
{
if (n < 0) {cout << "Negative.";}
else { cout << "Positive."; break; }
} // ^^^^^ break out of loop only if valid +ve integer
else
{
cout << "Not an integer.";
cin.clear();
cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin
}
}
cout << "\ndone.";
or you can simplify it even further like this:
或者您可以像这样进一步简化它:
while (!(cin >> n) || n < 0) // <<< note use of "short circuit" logical operation here
{
cout << "Bad input - try again: ";
cin.clear();
cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin
}
cout << "\ndone.";
回答by imulsion
int n;
while (!(cin >> n)||n<0)//as long as the number entered is not an int or negative, keep checking
{
cout << "Wrong input. Please, try again: ";
cin.clear();//clear input buffer
}
//only gets executed when you've broken out of the while loop, so n must be an int
cout << "Positive.";
cout << "\ndone.";//finished!
Should do what you want.
应该做你想做的。