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

当用户向int类型变量输入字符或字符串时,如何停止C++程序避免崩溃?

C++ int变量输入非数字内容时避免崩溃的实现方案

当std::cin尝试将字符/字符串输入到int类型变量时,会触发输入失败,cin的错误状态位会被置位,后续所有输入操作都会失效,最终导致程序逻辑异常甚至崩溃。
我们只要在每次读取数字后立即检测cin的错误状态,发现非法输入直接终止程序即可满足需求,修改后的完整代码如下:

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <cctype>

using namespace std;

int main() {
    unsigned int myNum, nTimes;
    bool Continue = true;
    char ContinueYN;
    vector<int> nDiv;


    while (Continue) {

        cout << "Insert a number.";
        cin >> myNum;
        // 输入合法性校验
        if (cin.fail()) {
            cout << "错误:输入内容不是合法数字,程序终止。" << endl;
            return 1;
        }
        cout << "How many numbers do you want to check?";
        cin >> nTimes;
        // 输入合法性校验
        if (cin.fail()) {
            cout << "错误:输入内容不是合法数字,程序终止。" << endl;
            return 1;
        }

        for (int I = 1; nTimes >= I; I++) {
            if (myNum % I == 0) {
                nDiv.push_back(I);
            }
        }

        cout << "The number is divisible for the following numbers: ";
        for (int i = 0; i < nDiv.size(); ++i) {
            cout << nDiv[i] << ' ';
        }
        
        cout << "\nPress any letter to continue or press n to stop\n";
        cin >> ContinueYN;
        ContinueYN = tolower(ContinueYN);

        if (ContinueYN == 'n') {
            Continue = false;
        }
        nDiv.clear();

        system("cls");
    }
    return 0;
}

修改说明

  • 新增<cctype>头文件,适配tolower函数的调用要求,避免部分编译器报未定义警告
  • 在每次读取无符号整数变量后,调用cin.fail()检测输入状态:如果返回true,说明用户输入的内容无法转换为合法的无符号整数,直接输出错误提示后终止程序即可
  • 无需额外清理输入缓冲区,直接终止程序后操作系统会自动回收所有进程资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:15:05