输入未正确读取条件语句
Input not being read properly by if condition 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语句(没有做您认为的事情:
if (userResponse == 'n' || 'N')
而是尝试一下:
if (userResponse == 'n' || userResponse =='N')
您需要在条件检查中单独定义每个逻辑操作。您将必须分别将userResponse
与n
和N
进行比较。
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;
}
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- CPP 带有条件语句的内在事物
- 如果验证容器的大小并在同一条件语句下访问元素,这是很好的做法吗?
- C++ - 这个条件语句写得正确吗?还是有更有效的写法?
- 条件语句简化 - C++
- 如何在C++中定义扩展到条件语句的宏?
- C++ 将二维数组索引与条件语句中的函数值进行比较
- 是否可以编写C++不使用任何条件语句交换输入的函数?
- C++未检查条件语句
- 输出错误命令的条件语句
- 是否可以删除此条件语句
- 如何在Char数组中搜索Char在IF条件语句中
- 可视化优雅C++代码:如何使用 while 循环和条件语句编写更高效的代码
- 输入未正确读取条件语句
- 我可以将循环用作如果其他条件语句
- 是否可以将结构与条件语句完全相同的字符串转换为可以读取和操作的语句?
- 简化重叠和条件语句
- 如果条件语句中的变量分配
- C++模板中的条件语句,只能由编译器基于条件包含
- 在条件语句中接受和使用 char