【发布时间】:2017-03-02 18:51:00
【问题描述】:
考虑这段代码:
string GameExit;
bool GameChoiceGo = true;
while (GameChoiceGo == true)
{
system("cls");
cout << "\n Are you sure you want to exit? (Yes or No) ";
cin >> GameExit;
if (GameExit == "y" || "Y" || "yes" || "Yes" || "YES")
{
cout << "User typed Yes";
Sleep(3000);
system("cls");
break;
}
if (GameExit == "n" || "N" || "no" || "No" || "NO")
{
cout << "User typed No";
Sleep(3000);
system("cls");
GameChoiceGo = false;
}
else
{
cout << "\nI'm sorry but, " << GameExit << " is not a acceptable choice. Type: Yes or No.\n\n\n";
Sleep(3000);
system("cls");
}
}
break;
这里,只有第一个语句被激活。即使用户输入"No" 或其他任何内容,它也会输出"user typed yes"。
如果我只用一个语句(即"y" 和"n")替换or statements,else-if statements 就可以工作。唯一的问题是,我想要用户可能在代码中键入的任何可能版本是和否。
任何想法为什么代码不能正常工作?
【问题讨论】:
-
你忘记了
else用于 if 语句的 no 分支。 -
你在用哪本书来学习 C++?
-
术语问题:
||是 运算符,x || y是 or-expression,而不是 statement我>。此外,它是一个 if-else-statement,而不是 else-if-statement。 (这可能看起来很挑剔,但代码序列else if并不特殊。) -
我希望它能像那样工作......想象一下我不必输入的额外字符......或复制粘贴。
-
很遗憾,我们没有针对初学者常见错误的规范欺骗。
标签: c++ if-statement logical-operators