简体   繁体   English

cin.fail 带有额外条件 C++

[英]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.所以我需要从用户那里得到输入,它必须是一个数字,我必须使用cin.fail()来检查它是否是一个数字。 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.最重要的是,数字必须是 0、1 或 2。我是 C++ 新手,所以还没有想出如何去做。

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.它检查输入是否为数字,但我不知道如何让它检查数字是 1、2 还是 0,如果不是,则再次询问,直到输入有效。

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' .假设变量menu是一个字符串,你可以在if语句中取字符串menu的第一个字符,检查该字符的十进制值是否在'0''3'的十进制数之间。

Change your if statement to this:将您的 if 语句更改为:

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.仅当第一个字符的十进制值小于字符'0'的十进制值或大于字符'3'的十进制值时,此代码才会运行,如果用户输入的长度超过此代码,则此代码将运行输入大于 1。

Assuming menu is an integer, witch makes sense, you can add the conditions you mentioned to your if :假设menu是一个整数,女巫是有道理的,您可以将您提到的条件添加到您的if

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

Live sample现场样品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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