我可以在 do while 循环中包含 "or" 操作数吗?
Can I include an "or" operand with my do while loop?
>"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
'是否等于1
或2
则应像这样检查
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">
相关文章:
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- 控制允许动态运行c++的并发操作数
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- Android NDK clang 编译器错误在 Windows 上显示'No such file or directory'
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- C++ 带有向量的 IF 计算操作数
- 是否所有C++运算符都接受操作数?
- 一元*运算符的操作数是否期望一个 prvalue
- 与'operator='不匹配(操作数类型'String'且"void")
- 模式"allocate memory or use existing data"
- N-API include an .so or dll
- 不正确的操作数类型 MSVC
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- 错误:类型"double()"和"double()"的操作数无效到二进制&quo
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 没有运算符"="与这些操作数匹配,JUCE 窗口演示应用程序
- 已解决 - C++ 的崇高文本中的"fatal error: opencv: no such file or directory"
- 我可以在 do while 循环中包含 "or" 操作数吗?