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

C++猜数字游戏do while循环字符输入无限输出Bug修复求助

解决猜数字游戏输入非整数时的无限循环问题

嘿,这个问题我之前也碰到过!当输入非整数字符时,cin >> b会读取失败,此时cin的错误标志位会被设置,后续所有的输入操作都会直接跳过,导致程序陷入无限循环。下面是修复后的完整代码,我会逐一说明关键修改点:

#include <iostream>
#include <cstdlib> // 用cstdlib替代stdlib.h,更符合C++标准
#include <ctime>   // 同理用ctime替代time.h
#include <conio.h>
#include <limits>  // 用于清空输入缓冲区的numeric_limits

using namespace std;

int main() { // 改为标准的int main()
    int a, b;
    char c;
    
    srand(time(NULL)); // 把随机数种子移到这里,只初始化一次,避免重复随机数
    START:
    system("cls");
    a = rand() % 100 + 1;
    cout << "Guess The hidden Number Between 1 and 100" << endl;
    
    do {
        cout << "\nEnter Any Number : ";
        cin >> b;
        
        // 新增:处理输入非整数的情况
        if (cin.fail()) {
            cout << "You haven't entered a number, please try again" << endl;
            cin.clear(); // 重置cin的错误状态,让它可以继续接收输入
            // 清空输入缓冲区里的所有无效字符,直到遇到换行符
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            continue; // 跳过本次循环的剩余逻辑,直接回到输入步骤
        }
        
        if (b > 100 || b < 1) {
            cout << " Try another number that is between 1 and 100!!!";
        } else {
            if (b > a) {
                cout << " =>Too Big";
            } else if (b < a) {
                cout << " =>Too Small";
            } else if (b == a) {
                cout << " =>You've Guess It!!!" << endl;
                break;
            }
        }
    } while (b != a);
    
    cout << "\nPress 'q' to start. Press else to close ";
    c = getch();
    if (c == 'q' || c == 'Q') goto START;
    
    return 0; // 标准main函数需要返回值
}

关键修改说明:

  • 处理输入失败状态:
    • 用cin.fail()检测输入是否失败(比如输入了字母)。
    • cin.clear()重置cin的错误标志位,否则后续的输入操作都会失效。
    • cin.ignore(...)清空输入缓冲区里的无效字符,避免这些垃圾数据影响下一次输入。
  • 标准C++规范调整:
    • 把stdlib.h和time.h换成cstdlib和ctime,这是C++标准库的头文件命名方式。
    • 将main()改为int main()并添加return 0;,符合C++标准要求。
  • 优化随机数生成:
    • 把srand(time(NULL))移到循环外面,只执行一次。如果放在START:标签内,短时间内重复启动游戏时,time(NULL)返回的时间戳可能相同,导致生成的随机数重复。

这样修改后,当你输入非整数时,程序就会输出指定的提示信息,然后等待你重新输入有效的数字啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:44:24