具有多个OR条件的While循环未退出循环

时间:2019-04-08 09:43:08

标签: c++

我试图运行一个while循环,当给定的输入不等于“ 1”,“ 2”或“ 3”时运行。

下面您将看到代码:

string get_menu_choice()
{
    string option;
    cout << "What action would you like to perform?" << endl;
    cout << "1. View a room."       << endl
         << "2. Create a new room." << endl
         << "3. Delete a room."     << endl;

    cout << "Enter your choice: ";
    cin >> option;

    while (option != "1" || option != "2" || option != "3")
    {
        cout << "Invalid input, enter in only 1, 2 or 3!" << endl;
        cout << "Enter your choice: ";
        cin  >> option;
    }

    return option;
};

运行此命令时,它不接受1、2或3作为可接受的答案,并不断循环浏览

我尝试将语句更改为 while(options != ("1" || "2" || "3")){//code here},但这对我来说也不成功。

1 个答案:

答案 0 :(得分:0)

您应编写如下代码:

while(option != "1" && option != "2" && option != "3")