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.";
输入非整数时,循环中断。我觉得我误解了cin.clear()
和cin.ignore()
的固有用法以及此循环期间cin
的状态。如果我删除cin.ignore()
,则循环变为无限。为什么是这样?我该怎么做才能使它成为一个优雅的循环?谢谢。
答案 0 :(得分:6)
在非整数分支中,您要调用更多cin
方法,以便将cin.good()
重置为true。
您可以将代码更改为以下内容:
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.";
或者您可以进一步简化它:
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.";
答案 1 :(得分:3)
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!
应该做你想做的事。