input validation

this works with numbers but how can i make it so,

if a user enter a letter instead of a number it'll say INVALID
my code rn just spams "its too low" to no end

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   do
  {
    //user input
    cout << "What is your guess? " << endl;
    cin >> userGuess; 
    cin.ignore(1000, 10);

    if (userGuess == compGuess)
    {
      cout <<"Thats right -- it's " << compGuess << endl;
      break;
    }
    else if (userGuess > compGuess)
    {
      cout <<"Thats too high -- guess again " << endl;
    }  
    else if (userGuess < compGuess)
    {
      cout <<"Thats too low -- guess again " << endl;
    }
    else
      cout <<"Invalid -- guess again " << endl; 
C++: Console User Input Done Right
http://www.lb-stuff.com/user-input
Hello pnwadike99,

Not enough code, but this can work.

I am guessing that "compGuess" is defined as an "int", but do not make people guess at this.

First you need to understand the difference between formatted and unformatted input.

Formatted input, as you are using, cin >> userGuess; detects the type of variable being used. If defined as an "int" it expects a number and a whole number at that to be entered. If you enter something that is not a whole number like a letter "cin" will fail and become unusable the rest of the program.

The opposite is unformatted input which will take everything up to and including the "\n". Usually used for strings.

When entering a number it is best to check the status of "cin" after input to make sure it worked.

This is untested, but I think it should work:
1
2
3
4
5
6
7
8
9
10
11
12
do
{
    //user input
    cout << "What is your guess? " << endl;
    
    while(!(cin >> userGuess;))
    {
        std::cerr << "\n     Invalid input! Try again.\n";

        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
    }

You can adjust the message as needed.

Line 6 does not need to be done after every formatted input, but is needed before an unformatted input using "std::getline".

Andy
Topic archived. No new replies allowed.