我可以在 do while 循环中包含 "or" 操作数吗?

Can I include an "or" operand with my do while loop?

本文关键字:or 操作数 包含 do while 循环 我可以      更新时间:2023-10-16

>"or"操作数,用于"do while"循环

我尝试在我的 do while 循环中包含"or"操作数

if(input2 == "1"){
    string input3;
    do {
        cout << "Which would you like to check?" << endl;
        cout << "1. Checking." << endl;
        cout << "2. Savings." << endl;
        cout << "3. Credit Card." << endl;
        cin >> input3;
            if(input3 != "1"||"2"||"3"){
            cout << "That is an invalid response. Please enter again." 
            <<endl;
            }
    } while(input3 != "1"||"2"||"3");
}

但它似乎不起作用。即使我输入 1、2 或 3,它仍然将其读取为无效响应。我做错了什么?

实际上你的状况有误。

布尔值 || 以错误的方式使用。如果要检查a'是否等于12则应像这样检查

a == 1 || a == 2

当你说input3 != "1"||"2"||"3"它会首先评估input3 != "1" || "2" || "3".这将始终计算为 TRUE,因为任何不为零并且可以转换为布尔值的东西都不会false C++

修改您的代码以使用正确的比较..

if(input2 == "1"){
    string input3;
    do {
        cout << "Which would you like to check?" << endl;
        cout << "1. Checking." << endl;
        cout << "2. Savings." << endl;
        cout << "3. Credit Card." << endl;
        cin >> input3;
            if(input3 != "1" && input3 != "2" && input3 != "3"){
            cout << "That is an invalid response. Please enter again." 
            <<endl;
            }
    } while(input3 != "1" && input3 != "2" && input3 != "3");
}

此代码:

input3 != "1"||"2"||"3"
表示(input3不是"1"(或

("2"(或("3"(

在这样的布尔表达式中使用时,像 C++ 中的"2"这样的字符串文本的计算结果将变为布尔值 true,因此您的表达式将始终被计算为 true。

我想你想要的是这个:

input3 == "1" || input3 == "2" || input3 == "3"
意思是输入3

是"1","2"或"3">

input3 != "1" && input3 != "2" && input3 != "3"

意思是 input3 既不是 "1"、"2" 也不是 "3">