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

C++程序问题求助:正确回答被判错,修改if else后无法运行

C++程序问题排查与修复

问题1:输入正确答案仍提示"Incorrect!"的原因

  • 使用cin >> test1读取字符串时,>>运算符以空格、换行等空白字符作为分隔符,只会读取第一个空格前的内容。当你输入"central processing unit"时,test1实际只存储了"central",和预期的完整字符串不匹配,因此会判定为错误。

问题2:修改if else后程序无法运行的常见原因

  • 多数是修改时犯了语法错误,比如漏写大括号、括号不配对、字符串引号未闭合等,导致编译器无法正常编译执行。

修复后的完整代码

#include <algorithm>
#include <iostream>
#include <string>

using namespace std;

int main() {
    string play;

    cout << "Do you want to play? ";
    cin >> play;

    if (play == "yes") {
        cout << "Ok, Let's Get Started! \n";
        
        string test1;
        cout << "What does CPU stand for? ";
        // 忽略之前cin操作残留的换行符,避免getline直接读取空内容
        cin.ignore();
        // 使用getline读取包含空格的整行输入
        getline(cin, test1);

        if (test1 == "central processing unit") {
            cout << "Correct!\n";
        } else {
            cout << "Incorrect!\n";
        }
    } else {
        cout << "Let's play next time!";
    }

    return 0;
}

核心修改点说明

  1. 换用getline读取整行:getline(cin, test1)可以读取包含空格的完整输入,解决了cin >>只能读取单个单词的问题。
  2. 清理输入缓冲区:调用cin.ignore()是因为之前用cin >> play后,输入缓冲区会残留一个换行符,不清理的话getline会直接将这个换行符当成输入内容,导致test1为空。
  3. 优化流程逻辑:把CPU提问的代码放到play == "yes"的分支内,用户选择不玩时就不会触发后续提问,逻辑更合理。

内容的提问来源于stack exchange,提问作者Arvin Calinog

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:35:48