Integer validation for input

前端 未结 3 870
忘掉有多难
忘掉有多难 2020-11-27 21:07

I tried to prompt user for input and do the validation. For example, my program must take in 3 user inputs. Once it hits non-integer, it will print error message and prompt

3条回答
  •  忘掉有多难
    2020-11-27 22:05

    When the reading fails, you set valid to false, so the condition in the while loop is false and the program returns input (which is not initialized, by the way).

    You also have to empty the buffer before using it again, something like:

    #include 
    #include 
    
    using namespace std;
    
    double read_input()
    {
        double input = -1;
        bool valid= false;
        do
        {
            cout << "Enter a number: " << flush;
            cin >> input;
            if (cin.good())
            {
                //everything went well, we'll get out of the loop and return the value
                valid = true;
            }
            else
            {
                //something went wrong, we reset the buffer's state to good
                cin.clear();
                //and empty it
                cin.ignore(numeric_limits::max(),'\n');
                cout << "Invalid input; please re-enter." << endl;
            }
        } while (!valid);
    
        return (input);
    }
    

提交回复
热议问题