Angella
Angella

Reputation: 1

How to fix the infinity loop in my code? I think it skips the second cin so it keeps looping

If i the input is not an int, it's going to give a infinite loop, i think it skips the second cin, but i don't know how to fix it.

cout << "Number of days : ";
int days;
cin >> days;
while(!cin){
    cout << "Invalid";
    cin >> days;
}

Upvotes: 0

Views: 50

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595837

When operator>> fails to parse input, it puts the stream into an error state that you need to explicitly clear before you can read from the stream again, eg:

cout << "Number of days : ";
int days;
while (!(cin >> days)) {
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Invalid";
}

Upvotes: 2

Related Questions