简体   繁体   English

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

[英]How to use the or statement (||) correctly, in an else-if statement

Consider this code: 考虑以下代码:

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;

Here, only the first statement is activated. 在这里,仅第一个语句被激活。 Even if the user types "No" or anything else, it will output "user typed yes" . 即使用户键入"No"或其他任何内容,它也会输出"user typed yes"

The else-if statements work if I replace the or statements with only one statement (ie "y" and "n" ). 如果我仅用一个语句(即"y""n" )替换or statements ,则else-if statements有效。 The only problem is, I want to have any possible version of yes and no that the user might type in the code. 唯一的问题是,我想要用户可以在代码中键入yes和no的任何可能版本。

Any ideas why the code is not working correctly? 有什么想法为什么代码不能正常工作?

I'm sorry, but you have to write GameExit == for every condition you want to check: 抱歉,您必须为要检查的每种情况编写GameExit ==

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

If you write if ("y") (which is basically what you are doing, only with more statements), the const char[] will decay to a const char* , and that pointer will be compared to 0 . 如果您编写if ("y") (基本上就是在做,只是使用更多的语句), const char[]将衰减为const char* ,并且该指针将与0进行比较。 Now, that pointer will never be null, as there will always be memory allocated for the string literal. 现在,该指针将永远不会为null,因为将始终为字符串文字分配内存。

A better solution is to (1) make an array with all the options, so that checking the conditions becomes a simple search or (2) convert the input to all lowercase for example, and compare that. 更好的解决方案是(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");

You can look up the functions if you do not know what they do :). 如果您不知道它们的作用,则可以查找它们:)。

Correct way using OR operator in "your" code is as below (note the explicit use of == statements between || operators): 在“您的”代码中使用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: The above answer is not intended to give the best programming practice in a similar situation but to give the specific answer to the OP with the minimal code change :) PS:以上答案并非旨在在类似情况下提供最佳编程实践,而是以最小的代码更改为OP提供特定答案:)

// -----

EDIT: Here is a better approach using STL. 编辑:这是使用STL的更好方法。 Note that (unsorted) array lookup requires linear search, whereas unordered_set , which is a hash set, has (on average) constant time lookup. 请注意,(未排序的)数组查找需要线性搜索,而作为哈希集的unordered_set具有(平均)恒定时间查找。 This will be faster especially when the yes, no etc. options are plenty. 这将更快,尤其是当“是”,“否”等选项很多时。

    #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" || ....

is incorrect. 是不正确的。 The correct method is: 正确的方法是:

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

and so on, both for the yes or no case. 等等,无论是肯定还是否。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM