You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 19:48:17