Home > Mobile >  Repeatedly non-stop output when I input char into int variable
Repeatedly non-stop output when I input char into int variable

Time:09-28

The folowing code tells user to input their age, the set to be input interger between 0 and 120, it is capable to deal with wrong input like 'M' or 133 or -1. Warning message goes like this:Warning message

case 1:                                // input age
        cout << "Enter your age: ";
        cin >>  age;
        
        if(age <= 0 || age > 120){     // if the input type or number was wrong, it goes here
            while(1){                
                cout << "Invalid input! Please enter again" << endl << ">>>";
                age = -1;
                cin >> age;
                if(age > 0 && age <= 120) {break;}
            }
        }

However, it'll go wrong if I input something like \ or [. Repeating Warning message

How can I solve this?

CodePudding user response:

lets walk through this. You type in something wrong and enter the if clause. In here you enter the while loop and ask the user again for a input. This input is instantly answered because there is still something in the input stream. Therefore you need to flush the cin stream before asking again for an input (You can place the flush in for example line 4).

You should be able to clear the stream with a command like this: How do I flush the cin buffer?

Unfortunately I'm not able to test that out by myself but you can give it a try and I hope it helps!

CodePudding user response:

By emptying the keyboard buffer before a new entry.

#include <iostream>
#include <limits>
using namespace std;

int main()
{
    int age;
    cout << "Enter your age: ";
    cin >> age;

    while(age <= 0 || age > 120)
    {
        cout << "Invalid input! Please enter again" << endl << ">>>";
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cin >> age;
    }

    return 0;
}
  • Related