Mayron
Mayron

Reputation: 2394

C++ How to enter user values without breaking program

I am trying to get an integer from the user but if they type "ckefkfek" it will cause the program to spam and break. I also want them to enter a float but I get the same problem and no clue how to check for this.

int option = 0;
while (option != 3)
{
    cout << "Enter 1, 2, or 3: ";
    cin >> option;
    switch (option)
    {
        case 1:
            cout << "Enter a float: ";
            float myfloat;
            cin >> myfloat;
            myFunc(myfloat); // must be a float for this function to work.
            break;
        case 2:
            // do stuff
            break;
        case 3:
            // do stuff
            break;
        default:
            cout << endl << "Not a valid option." << endl;
            break;
    }
}

How can I do this without constant errors? Thank you!

Upvotes: 1

Views: 104

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171253

bool input_ok = false;
while (!input_ok)
{
  cout << "Enter 1, 2, or 3: ";
  if (cin >> option)
  {
    input_ok = true;
    ...
  }
  else
  {
    cout << "Stop being silly\n";
    std::string dummy;
    if (cin >> dummy)
      cin.clear();
    else
      throw std::runtime_error("OK, I'm not playing any more");
  }
}

Basically if the input can fail, you need to test whether it failed. You test that by checking the state of the stream after reading from it, with cin >> option; if (cin) ..., or by combining the read and test like this: if (cin >> option) ...

If input fails, read whatever couldn't be parsed as an integer and discard it, and try again.

Upvotes: 5

Related Questions