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

Ste*_*yes 0 c++ if-statement logical-operators

考虑以下代码:

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;
Run Code Online (Sandbox Code Playgroud)

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

else-if statements工作,如果我取代or statements只有一个声明(即"y""n").唯一的问题是,我希望有任何可能的yes和no版本,用户可能会输入代码.

有什么想法为什么代码不能正常工作?

Rak*_*111 8

对不起,但你必须为GameExit ==你要检查的每个条件写:

if (GameExit == "y" || GameExit == "Y" || GameExit == "yes" || GameExit == "Yes" || GameExit == "YES")
Run Code Online (Sandbox Code Playgroud)

如果你写if ("y")(这基本上就是你正在做的,只有更多的语句),const char[]它将衰减为a 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");
Run Code Online (Sandbox Code Playgroud)

如果你不知道他们做了什么,你可以查看这些功能:).