输入未正确读取条件语句

Input not being read properly by if condition statement

本文关键字:条件 语句 读取 输入      更新时间:2023-10-16

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

如果我输入字符'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语句(没有做您认为的事情:

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

而是尝试一下:

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

您需要在条件检查中单独定义每个逻辑操作。您将必须分别将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++;
}

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

||操作员在单个条件上不起作用,必须有两个完整的条件,每个条件都在。尝试用此行替换IF语句:

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

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

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

否则您实际上正在测试

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

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

userResponse == 'y'

如果userResponse'y'0,则返回值1。操作员||如果左或右表达式不为零,则返回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,因为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;
}