TeckBeng
TeckBeng

Reputation: 27

How to solve the loop in cin.fail()

Any idea why this happen?

sample run

void askNQ(int &noq)
{
    bool x = true;
    while (x)
    {
        int i;
        cout << "How many questions would you like(out of " << noq << ")?" << endl;
        cin >> i;

        if (cin.fail())
        {
        cin.clear();
        cin.ignore();
        cout << "Sorry, that is not valid." << endl;
        x = true;
        }
        else if (i > noq)
        {
            cout << "Sorry, that is too many." << endl;
            x = true;
        }
        else if (i <= 0)
        {
            cout << "Sorry, that is too less." << endl;
            x= true;
        }
    }
}

Upvotes: 0

Views: 59

Answers (2)

saeid zamani
saeid zamani

Reputation: 71

You should enter numeric in command line, Since the variable "i" is integer.

Upvotes: 0

cin.ignore(); is in fact a call to cin.ignore(1, char_traits<char>::eof());.

So you aren't cleaning the buffer out of any leftover newlines.

The following should fix your problem:

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

It clears the next newline character, no matter how far it is in the buffer (for all practical purposes).

Upvotes: 1

Related Questions