0

Been working on a simple school project but I've run into a small problem in regards to validation of user input via the use of a while loop. The following code is used to do so:

cout << "How much woud you like to bet?[100, 300, 500]" << endl;
    cin >> int_input;
    if (cin.fail()){
        int_input = 0;
    }

     //Validate check
     while(int_input!=100 && int_input!=300 && int_input!=500){
        cout << "Please enter a valid bet [100, 300, 500]" << endl;
        cin >> int_input;
        if (cin.fail()){
            int_input = 0;
        }
     }

The issue arises when a non-integer is entered and the loop ends up spitting out the cout msg over and over again, skipping the request for new input. I assume that a non-integer always returns true for the while loop, but the program should still ask for user input, right?

The cin.fail is a recent addition and might not be necessary as it doesn't solve the problem, although I leave the code as it as it is.

Ghal
  • 5
  • 1

1 Answers1

3

If you have an error on the stream, you set your value to 0. So the loop is run again... and the error's still on the stream. Repeat.

You need to clear the error flag.

cin.clear();

Then extract enough "bad" data to get to the good part, or you'll just be right back where you started.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055