6

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 for input again. Here is how my program going to be look like when running :

Enter number: a

Wrong input

Enter number: 1

Enter number: b

Wrong input

Enter number: 2

Enter number: 3

Numbers entered are 1,2,3

And here is my code:

double read_input()
{
    double input;
    bool valid = true;
    cout << "Enter number: " ;
    while(valid){
        cin >> input;
        if(cin.fail())
        {
            valid = false;
        }
    }
    return input;
}

My main method:

int main()
{
double x = read_input();
double y = read_input();
double z = read_input();
}

When my first input is non-integer, the program just exits by itself. It does not ask for prompting again. How could I fixed it? Or am I supposed to use a do while loop since I asking for user input.

Thanks in advance.

  • we have to see more code.. have you checked it with a debugger? could be a crash... – Karoly Horvath Jun 05 '13 at 07:52
  • inside the main method I just write double x = read_input(); double y = read_input(); double z = read_input(); Am I doing the wrong way? –  Jun 05 '13 at 07:53
  • Also see [How to check if the input is a valid integer without any other chars?](https://stackoverflow.com/q/20287186/608639) – jww Jun 28 '18 at 04:07

3 Answers3

8

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);
}
Djon
  • 2,230
  • 14
  • 19
  • When I put a cout in else statement and I typed in non-integer, the error message itself just keep looping. –  Jun 05 '13 at 07:58
  • I cannot test the code, but Ideone has the same output, let me check why. – Djon Jun 05 '13 at 08:14
  • @Carol It works now, I guess it was the order between `clear` and `ignore`: http://ideone.com/fl4IMK – Djon Jun 05 '13 at 08:29
  • Okay thanks a lot. But why you initialize the input as -1 and what's the use of flush? –  Jun 05 '13 at 08:35
  • 1
    @Carol In C and C++ I always initialize my values (Java complains about it, so I always do it now), you cannot exit the function without reading a correct value so it is not necessary. Flush is to make sure that the standard input buffer is correctly displayed, I was thought that way, you can remove it if you want. (endl is '\n' + flush I think). – Djon Jun 05 '13 at 08:38
  • Oh okay thanks a lot. I used cin.clear() and getline method and it works now. –  Jun 05 '13 at 08:45
  • I reused this example, it still causes slight hiccups when you have multiple calls to the function and you enter input like '20a5'. It stores the 20 properly, but the 'a' section then gets read by the next function. While not a perfect fix, calling cin.clear and cin.ignore after switching input to true. This is all assuming I don't have a bug in my own code of course. – The_Redhawk Feb 19 '21 at 17:41
0

Your question did get myself into other issues like clearing the cin on fail() --

double read_input()
{
double input;
int count = 0; 
bool valid = true;
while(count != 3) {
    cout << "Enter number: " ;
    //cin.ignore(); 
    cin >> input; 
    if(cin.fail())
    {
        cout << "Wrong Input" <<endl;
        cin.clear(); 
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    }
    else 
            count++;
}
return input;
}
Manoj Awasthi
  • 3,460
  • 2
  • 22
  • 26
0

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.

A4L
  • 17,353
  • 6
  • 49
  • 70
  • Okay thanks alot. I used cin.clear() and getline in else statement and it works now –  Jun 05 '13 at 08:44