仅识别的 int 输入为 1

Only int input recognized is 1

本文关键字:输入 int 识别      更新时间:2023-10-16

无论我输入什么,此函数中唯一识别的 int 是 1。如果选择了任何其他内容,则 do-while 循环将重复。该代码在没有任何OR运算符的情况下也能正常工作,例如"while (input != 0)"

void menu()
{
    int input = -1;
    do
    {
    cout << "         ---------------" << endl << "         -     OU6     -" << endl << "         ---------------" << endl;
    cout << "1. Read a transaction from the keyboard." << endl;
    cout << "2. Print all transactions to console." << endl;
    cout << "3. Calculate the total cost." << endl;
    cout << "4. Get debt of a single person." << endl;
    cout << "5. Get unreliable gold of a single person." << endl;
    cout << "6. List all persons and fix." << endl;
    cout << "0. Save and quit application." << endl;
    cin >> input;
    } while (input != (0 || 1 || 2 || 3 || 4 || 5 || 6));
    if (input == 0)
    {
        cout << "0!" << endl;
        cin.get();
    }
    if (input == 1)
    {
        cout << "1!" << endl;
        cin.get();
    }
    if (input == 2)
    {
        cout << "2!" << endl;
        cin.get();
    }
}

这一行:

while (input != (0 || 1 || 2 || 3 || 4 || 5 || 6))

不做你认为它做的事情。您不能像这样组合测试。您编写的内容基本上等同于 while (input != true) ,并且由于true等于 1,您可以看到唯一有效的选项是 input == 1 .

您需要将其更改为例如

while (input < 0 || input > 6)

您正在将input0 || 1 || 2 || 3 || 4 || 5 || 6进行比较。

||的结果是一个布尔值,一个真值。

0 || 1 || 2 || 3 || 4 || 5 || 6 

相当于

0 != 0 || 1 != 0 || 2 != 0 || 3 != 0 || 4 != 0 || 5 != 0 || 6 != 0

这是(希望很明显)正确的。

而一个bool可以隐式转换为inttrue转换为1,所以这就是你唯一有效输入的原因;你的条件等价于input != 1

翻译成逻辑的英语短语"如果输入不是 0 或 1"是"如果输入不是 0 并且输入不是 1"。

这会给你

while (input != 0 && input != 1 && input != 2 && input != 3 && input != 4 && input != 5 && input != 6) 

这是一个严重的混乱,写得更明智的是

while (input < 0 || input > 6)

或者,更迂回,

while (!(input >= 0 && input <= 6))

正如其他人指出的那样,使用 ||(逻辑 OR) 将使您的条件等同于 (input != 1)

我建议在这里使用开关/案例语句和一个附加条件:

void menu()
{
    int input = -1;
    bool inputIsValid = false ;
    do
    {
      cout << "         ---------------" << endl << "         -     OU6     -" << endl << "         ---------------" << endl;
      cout << "1. Read a transaction from the keyboard." << endl;
      cout << "2. Print all transactions to console." << endl;
      cout << "3. Calculate the total cost." << endl;
      cout << "4. Get debt of a single person." << endl;
      cout << "5. Get unreliable gold of a single person." << endl;
      cout << "6. List all persons and fix." << endl;
      cout << "0. Save and quit application." << endl;
      cin >> input;
      switch ( input ) 
      {
        case 0:
          cout << "0!" << endl;
          cin.get();
          inputIsValid = true;
        break;
        /* other cases here... */ 
        default:
          inputIsValid = false ;
        break;
      }
    } while ( false == inputIsValid ) ;
}
相关文章: