如果条件语句没有正确读取输入

时间:2018-02-23 20:39:09

标签: c++ if-statement

有人会认为这很容易,但由于某些奇怪的原因,我的条件语句忽略了用户输入。

如果我输入一个字符'N'或'n',它仍然执行条件语句的'Y'部分,看看:

while (i < 10) {
        cout << "Would you like "<< nameOfDish[i] << "? Please enter Y or N.\n";
        cin >> userResponse;



        if (userResponse == 'y' || 'Y')
        {
            cout << "How many orders of " << nameOfDish[i] << " would you like?\n";
            cin >> quantityOfDish[i];
            if (quantityOfDish[i] == 0) {
                cout << "I suppose you're entitled to change your mind.\n";
            }
            else if (quantityOfDish[i] < 0) {
                cout << "Your generosity is appreciated but I must decline!\n";
                quantityOfDish[i] = 0;
            }

            i++;
        }

        else if (userResponse == 'n' || 'N')
        {
            i++;
        }

        else
        {
           cout << "I think you mumbled NO, so I'll just go on.\n";
           i++;
        }

    }

是否有任何特殊原因为什么尽管输入'n'仍然会在条件块中进入'Y'?

我已经调试了调试器中的代码,并且我注意到正在正确读取userResponse变量。然而,if条件似乎没有正常工作。谢谢!

5 个答案:

答案 0 :(得分:2)

此声明(以及您的其他if声明)没有按照您的想法执行:

(?,)

请改为尝试:

if (userResponse == 'n' || 'N') 

答案 1 :(得分:0)

您需要在条件检查中单独定义每个逻辑操作。您必须分别将userResponsenN进行比较。

if (userResponse == 'y' || userResponse == 'Y')
{
    cout << "How many orders of " << nameOfDish[i] << " would you like?\n";
    cin >> quantityOfDish[i];
    if (quantityOfDish[i] == 0) {
        cout << "I suppose you're entitled to change your mind.\n";
    }
    else if (quantityOfDish[i] < 0) {
        cout << "Your generosity is appreciated but I must decline!\n";
        quantityOfDish[i] = 0;
    }

    i++;
}

答案 2 :(得分:0)

自从我在C ++工作以来已经有一段时间了,但我很确定我知道发生了什么。

||运算符不适用于单个条件,必须有两个完整的条件,每个条件一个。尝试用这一行替换你的if语句:

if (userResponse == 'y' || userResponse == 'Y')

答案 3 :(得分:0)

也许你习惯了SQL?您需要重复userResponse

if userResponse == 'n' || userResponse == 'N'

否则你实际上正在测试

if userResponse is 'n' or  the char'N' exists

答案 4 :(得分:0)

正如其他人所指出的,此代码中的错误是if语句。但是,我觉得这可能需要一些澄清。每个C ++表达式都返回一个值。例如。

userResponse == 'y'
如果1userResponse,则

返回值'y',如果是0则返回||。如果左表达式或右表达式非零,则运算符1返回if

最后,if (5) cout << "X"; else cout << "Y"; 语句检查表达式是零还是非零。所以,

X

将打印if (0) cout << "A"; else cout << "B";

B

将打印if (userResponse == 'y' || 'Y')

现在,我们可以开始理解为什么你的代码编译成功,但没有做你想要的。

||

在此示例中,1运算符将始终返回'Y',因为右侧的表达式89将始终为非零(具体而言,它将为{{1}因为C ++字符只是ASCII对应数字的别名)。当然,

if (userResponse == 'y' || userResponse == 'Y')

按预期工作。但是有一个更好的解决方案,那就是switch语句,其目的是处理这样的情况。这是在行动:

switch (userResponse) {
  case 'y':
  case 'Y':
    //The user answered yes, handle that situation here.
    break;
  case 'n':
  case 'N':
    //The user answered no, handle that situation here.
    break;
  default:
    // The user did not enter a valid answer, 
    // handle that situation here.
    break;
}