C++ Checking for an integer.

淺唱寂寞╮ 提交于 2019-12-18 05:02:24

问题


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.";

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.


回答1:


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.";



回答2:


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.



来源:https://stackoverflow.com/questions/18567483/c-checking-for-an-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!