reimotaavi
reimotaavi

Reputation: 57

cin.fail with extra conditions C++

So I need to get input from the user which has to be a number and I have to use cin.fail() to check if it is a number. On top of that, the number has to be either 0, 1 or 2. I'm new to C++ so haven't figured out how to do it.

Here's the part of the code. It checks if the input is a number, but I do't know how to make it check if the number is 1, 2 or 0 and if not then ask again until the input is valid.

do {
  input = false;
  cout << "Enter a number from the menu: ";
  cin >> menu;

  if (cin.fail()) {
    cout << "Invalid input!" << endl;
    input = true;
    cin.clear();
  }
  cin.ignore(numeric_limits<streamsize>::max(), '\n');

} while (input);

cout << "Valid input!";

Upvotes: 1

Views: 113

Answers (2)

xBm
xBm

Reputation: 69

Assuming the variable menu is a string ,you can take the first character of the string menu in the if statement and check if the decimal value of the character is between the decimal number of '0' to '3'.

Change your if statement to this:

if (menu[0] < '0' || menu[0] > '3' || menu.length() > 1)
{
    // Error code
}

This code will run only if the decimal value of the first character is smaller than the decimal value of the char '0' or bigger than the decimal value of the char '3' and this code will run if the length of the input the user entered is bigger than 1.

Upvotes: 1

anastaciu
anastaciu

Reputation: 23802

Assuming menu is an integer, witch makes sense, you can add the conditions you mentioned to your if:

if (cin.fail() || menu < 0 || menu > 2)

Live sample

Upvotes: 1

Related Questions