C++中字符串条件判断语句失效问题求助
问题原因及修正方案
问题根源
你的代码中if和else if的条件判断写法错误,导致第一个分支永远被执行。
在C++中,逻辑或运算符||要求两侧都是布尔表达式。你写的answer == "yes" || "yeah"里,"yeah"是一个非空字符串字面量,会被隐式转换为布尔值true。这意味着整个条件answer == "yes" || true永远为真,不管answer输入什么,都会进入第一个分支输出Thats great!。
修正方法
对每个逻辑或的分支,都要完整写出变量与目标值的比较:
- 将
if (answer == "yes" || "yeah")改为if (answer == "yes" || answer == "yeah") - 将
else if (answer == "no" || "nah")改为else if (answer == "no" || answer == "nah")
修正后的完整代码
#include <iostream> #include <string> using namespace std; int main() { std::string answer; cout << "Hello!" << '\n'; cout << "Do you have a dog?" << endl; cin >> answer; if (answer == "yes" || answer == "yeah") { cout << "Thats great!"; } else if (answer == "no" || answer == "nah") { cout << "Aww, thats too bad..."; } else { cout << "Umm, I didn't get that." << '\n'; cout << "Could you repeat that again?" << endl; } return 0; }
内容的提问来源于stack exchange,提问作者Yashka
相关产品推荐
相关产品推荐

