如何在 else-if 语句中正确使用 or 语句 (||)



请考虑以下代码:

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.nnn";
Sleep(3000);
system("cls");
}
}
break;

在这里,仅激活第一个语句。即使用户键入"No"或其他任何内容,它也会输出"user typed yes"

如果我只用一个语句替换or statements,则else-if statements工作(即"y""n")。唯一的问题是,我希望用户可能在代码中输入任何可能的"是"和"否"版本。

知道为什么代码无法正常工作的任何想法?

很抱歉,但您必须为要检查的每个条件编写GameExit ==

if (GameExit == "y" || GameExit == "Y" || GameExit == "yes" || GameExit == "Yes" || GameExit == "YES")

如果你写if ("y")(这基本上就是你正在做的事情,只是有更多的语句),const char[]将衰减为const char*,并且该指针将与0进行比较。现在,该指针永远不会为 null,因为始终会为字符串文本分配内存。

更好的解决方案是 (1) 创建一个包含所有选项的数组,以便检查条件成为简单的搜索或 (2) 例如将输入转换为全部小写,并进行比较。

// 1)
std::vector<std::string> options = { "y", "Y", "yes", "Yes", "YES" };
if (std::find(options.begin(), options.end(), GameExit) != options.end());
// or
if (std::any_of(options.begin(), options.end(), [&GameExit](const auto& value) { 
return GameExit == value;
}); 
// 2)
std::transform(GameExit.begin(), GameExit.end(), GameExit.begin(), ::tolower);
if (GameExit == "y" || GameExit == "yes");

如果您不知道函数:)做什么,可以查找它们。

在"your"代码中使用OR运算符的正确方法如下(请注意||运算符之间显式使用==语句):

if (GameExit == "y" || GameExit =="Y" || GameExit =="yes" || GameExit =="Yes" || GameExit =="YES")
{
cout << "User typed Yes";
Sleep(3000);
system("cls");
break;
}
if (GameExit == "n" || GameExit =="N" || GameExit =="no" || GameExit =="No" || GameExit =="NO")
{
cout << "User typed No";
Sleep(3000);
system("cls");
GameChoiceGo = false;
}

PS:上面的答案并不是为了给出类似情况下的最佳编程实践,而是用最少的代码更改给出OP的具体答案:)

// -----

编辑:这是使用STL的更好方法。请注意,(未排序的)数组查找需要线性搜索,而unordered_set是一个哈希集,具有(平均)恒定时间查找。这将更快,特别是当是,否等选项很多时。

#include <unordered_set>
...
// These sets can be as large as possible or even dynamically 
//  updated while the program is running. insert, remove, lookup will
// all be much faster than a simple array.
unordered_set<string> ySet{"y", "Y", "yes", "Yes", "YES"};
unordered_set<string> nSet{"n", "N", "no", "No", "NO"};
if (ySet.find(GameExit) != ySet.end())
{
cout << "User typed Yes";
Sleep(3000);
system("cls");
break;
}
if (nSet.find(GameExit) != nSet.end())
{
cout << "User typed No";
Sleep(3000);
system("cls");
GameChoiceGo = false;
}
...

您需要为每个表达式定义一个完全相等,如下所示:

if ( gameExit == "y" || gameExit == "Y" ) {}
GameExit == "y" || "Y" || ....

是不正确的。正确的方法是:

GameExit == "y" || GameExit == "Y" || ....

等等,无论是"是"还是"否"情况。

相关内容

  • 没有找到相关文章

最新更新