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

后端 未结 2 324
抹茶落季
抹茶落季 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: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::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.

提交回复
热议问题