1
votes

Let me show you my source at first.

#include <iostream>
#include <limits>

using namespace std;

int main() {
    int n;

    while (true) {
        cout << "Type >> ";
        cin >> n;

        if (cin.fail()) {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Not a number" << endl;

            continue;
        }

        if (n % 2)
            cout << "odd";
        else
            cout << "even";

        cout << endl;
    }

    return 0;
}

Well, This code can run without any problems. however, if I swap between cin.clear() and cin.ignore(), then type character(not integer), it stucks in infinite loop. (consult next code)

#include <iostream>
#include <limits>

using namespace std;

int main() {
    int n;

    while (true) {
        cout << "Type >> ";
        cin >> n;

        if (cin.fail()) {               
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cin.clear();
            cout << "Not a number" << endl;

            continue;
        }

        if (n % 2)
            cout << "odd";
        else
            cout << "even";

        cout << endl;
    }

    return 0;
}

I wonder sequence is neccesary between cin.clear() and cin.ignore(). if it is, I wanna know why it needs sequence.

Thx for read my Question. I will be very appreciated for any your replies. sorry for inarticulate Writing.

2

2 Answers

0
votes

While cin.fail() is true, any attempts to read from the stream will - eh - fail.

Calling cin.clear() removes the failure flags from the stream, and thus enables input again.

0
votes

Let's look at the second snippet step by step:

if (cin.fail()) { 

If we enter this, the stream is already bad. So the input operation

cin.ignore(numeric_limits<streamsize>::max(), '\n');

fails immediately and does nothing. Thus, after

cin.clear();

the garbage input is still in the stream and makes

cin >> n;

fail again, without even waiting for input, which gets us back to the beginning.

If you swap the calls around (like in the first snippet), the clear will make the stream "good" again, then ignore successfully gets rid of the garbage input, and the cin >> n; will work as expected.