C ++检查整数。 [英] C++ Checking for an integer.
问题描述
C ++的新增功能。处理错误时使问题正确循环。我正在尝试检查用户输入是否为整数,并且为正数。
New to C++. Having issues correctly looping while handling errors. I am trying to check if user input is an integer, and is positive.
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.";
输入非整数时,循环中断。我觉得我误会了 cin.clear()
和 cin.ignore()
的固有用法以及状态在此循环中的 cin
。如果删除 cin.ignore()
,循环将变为无限。为什么是这样?我怎样做才能使它成为一个功能完善的循环?谢谢。
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
方法,因此 cin.good()
会重置为true。
In your non-integer branch you are invoking further cin
methods so cin.good()
gets reset to 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.";
这篇关于C ++检查整数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!