Integer validation for input

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 <iostream>
#include <limits>

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<streamsize>::max(),'\n');
            cout << "Invalid input; please re-enter." << endl;
        }
    } while (!valid);

    return (input);
}

Leave a Comment