C++正在检查整数

C++ Checking for an integer.

本文关键字:整数 检查 C++      更新时间:2023-10-16

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(),循环将变为无穷大。为什么会这样?我该怎么做才能把它变成一个功能优雅的循环呢?非常感谢。

在非整数分支中,您正在调用更多的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.";
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!

应该做你想做的事。