Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

cin - C++ Checking for an integer.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, '
'); // NB: preferred method for flushing cin
    }
}

cout << "
done.";

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, '
'); // NB: preferred method for flushing cin
}

cout << "
done.";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...