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

为什么我的C++常识测验程序在答案错误时会无限打印错误提示?

问题排查与修复说明

核心问题原因

你遇到的无限打印问题和代码逻辑错误有直接关系,具体问题如下:

  • while循环未添加重新输入逻辑:你写的while循环仅执行了错误提示和尝试次数累加,完全没有在循环内重新读取用户输入的spells变量,导致spells永远保留第一次输入的错误值,循环判断条件spells != "Leonardo Da Vinci"永远成立,自然会无限打印错误提示。
  • 输入读取方法不符合需求:std::cin >> spells读取字符串时会以空格作为终止符,而正确答案Leonardo Da Vinci包含多个空格,即使用户输入了完全正确的答案,spells也只会存入第一个空格前的Leonardo,永远不会和正确答案匹配。
  • 变量未初始化:int tries;定义后没有赋值初始值,直接执行tries++属于C++的未定义行为,可能出现计数异常。

和参考代码的核心差异

你参考的示例代码循环内部必然包含了重新读取用户输入的逻辑,同时大概率处理了带空格输入的场景,这两点是你漏写的核心内容。

修复后的参考代码

#include <iostream>
#include <string>
#include <limits>

int main() {
    // 初始化变量
    int tries = 0;
    std::string hamon;
    std::string spells;
    int you;

    std::cout << " This is the G.K Test.\n ";
    std::cout << " Start?\n ";
    std::cin >> hamon;

    if (hamon == "Yes") {
        std::cout << " Great . The first question is: Who created the Mona "
                     "Lisa painting?\n ";
        // 清理cin读取hamon后留在缓冲区的换行符,避免后面getline读空
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        // 用getline读取整行,支持带空格的答案
        std::getline(std::cin, spells);

        if (spells == "Leonardo Da Vinci") {
            std::cout << " correct answer ";
        }

        while (spells != "Leonardo Da Vinci") {
            std::cout << "Wrong answer! Please try again:\n";
            tries++;
            // 循环内重新读取用户输入
            std::getline(std::cin, spells);
        }
    }

    std::cin >> you;
    return 0;
}

内容的提问来源于stack exchange,提问作者Aquasplash Gamer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:36:07