Integer validation for input

前端 未结 3 863
忘掉有多难
忘掉有多难 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 21:58

    The problem is in the while condition

    bool valid = true;
    while(valid){
    

    You loop until you get a non valid input, this absolutly not what you want! loop condition should be like this

    bool valid = false;
    while(! valid){ // repeat as long as the input is not valid
    

    Here is a modified version of your read_double

    double read_input()
    {
        double input;
        bool valid = false;
        while(! valid){ // repeat as long as the input is not valid
            cout << "Enter number: " ;
            cin >> input;
            if(cin.fail())
            {
                cout << "Wrong input" << endl;
    
                // clear error flags
                cin.clear(); 
                // Wrong input remains on the stream, so you need to get rid of it
                cin.ignore(INT_MAX, '\n');
            }
            else 
            {
                valid = true;
            }
        }
        return input;
    }
    

    And in your main you need to ask for as may doubles as you want, for example

    int main()
    {
        double d1 = read_input();
        double d2 = read_input();
        double d3 = read_input();
    
        cout << "Numbers entered are: " << d1 << ", " << d2 << ", " << d3 << endl;
    
        return 0;
    }
    

    You may also want to have a loop where you call read_double() and save the returned values in an array.

提交回复
热议问题