简体   繁体   中英

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!";

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM