-1

The folowing code tells user to input their age, it is 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?

MaleWalk
  • 3
  • 2
  • 3
    whats the type of `age` ? When input fail the stream is in an error state, you have to reset it before you can read again – 463035818_is_not_an_ai Sep 28 '22 at 08:20
  • As the answer below says. First read your input as a string. Second check is that string has the form of an integer. Third convert that string to an integer. Fourth check if that integer is in the range you require. I think beginners don't take this obvious approach because they don't know how to do steps 2 and 3, but really they are not difficult. For instance the function [stoi](https://en.cppreference.com/w/cpp/string/basic_string/stol) can achieve both steps. – john Sep 28 '22 at 08:28

2 Answers2

0

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!

0

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;
}
CGi03
  • 452
  • 1
  • 3
  • 8