How to check for a valid user input in C++

后端 未结 2 322
抹茶落季
抹茶落季 2021-01-13 11:48

I\'m trying to build the Bulls & Cows game in C++. I\'ve implemented most of the logic. The game runs continuously with the use of an infinite loop and generates a ran

相关标签:
2条回答
  • 2021-01-13 12:26

    Try out cin.ignore(). It'll help you flush the cin buffer.

    0 讨论(0)
  • 2021-01-13 12:41

    There's nothing wrong with the way you read the user input, it just doesn't check for the input type before assigning the value into your 'guess' variable.

    So, if an user put any value that isn't accepted by the integer type it would crash your application generating this infinite loop.

    To protect your integer variable from wrong user inputs you must replace your direct input assignment:

    cin >> guess;
    

    By a protected one:

    while(!(cin >> guess) || (guess < 1000)){
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input. Please, try again: ";
    }
    

    Into the while above you can see the "numeric_limits::max()" which is explained here:

    Returns the maximum finite value representable by the numeric type T. Meaningful for all bounded types.

    At the end you have a while holding the user into this reading loop while its input is under 1000 (as requested) or isn't a valid integer.

    0 讨论(0)
提交回复
热议问题