6

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(),循环将变为无限。为什么是这样?我该怎么做才能使它成为一个运行优雅的循环?谢谢你。

4

2 回答 2

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.";
于 2013-09-02T07:19:00.580 回答
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!

应该做你想做的。

于 2013-09-02T07:17:26.807 回答