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

C++如何设置cin仅允许输入最多4个数字并避免输入异常死循环

问题根因
  • 输入4个数字后流程不终止:main函数中使用了while(true)死循环,GameBoy函数执行完成后会立刻重新触发执行,因此会反复要求用户输入,无自动终止逻辑。
  • 输入非法内容触发无限循环:当输入内容超出int类型取值范围、或包含非数字字符时,cin会进入失败状态,后续所有cin读取操作都会直接失败跳过,不会再等待用户输入,程序就会无限重复执行输出逻辑。

另外你代码中的if (sum != average && average == sum)判断逻辑永远为假,不会触发该分支的输出。

修复代码
#include <iostream>
#include <limits>
using namespace std;

void GameBoy ()
{
    cout<< "\nYou think you are this badass hacker so...." <<endl;
    cout<< "Please enter the correct combination of 4 numbers..." <<endl;

    int a {}, b {}, c {}, d {};
    cin >> a >> b >> c >> d;

    // 校验输入状态
    if (cin.fail()) {
        // 清空错误标记
        cin.clear();
        // 清空输入缓冲区所有残留内容
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "输入无效,请输入4个合法整数" << endl;
        return;
    }

    double sum = a + b + c + d;
    double average = sum / 4;
    cout << "平均值:" << average << endl;

    // 可根据实际业务修改判断逻辑,原逻辑永远不成立
    cout << "You're still a goober :-P" << endl;
}

int main()
{
    // 不需要循环执行的话,直接单次调用GameBoy即可
    GameBoy();

    /* 如果需要保留循环,可增加退出条件,示例如下:
    char op;
    while (true) {
        GameBoy();
        cout << "输入q退出,输入其他键继续:" << endl;
        cin >> op;
        if (op == 'q' || op == 'Q') break;
    }
    */
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:24:02