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

如何在C++中判断输入是否为数字?现有代码识别异常如何解决?

问题原因
  • 错误使用isdigit()函数:该函数的作用是判断单个字符是否属于数字字符(对应ASCII编码范围48~57,即字符'0'到'9'),要求入参是unsigned char转int的值或者EOF。你直接将存储输入数值的int变量传入,比如输入数字5,input存储的是整数5,远小于48,所以isdigit()永远返回假,自然始终提示不是数字。
  • 输入校验逻辑缺失:你直接用cin >> int类型变量读取输入,如果用户输入的内容本身无法转为整数,cin会直接进入失败状态,input的值不会被更新,你也没有校验cin的读取状态,逻辑本身存在漏洞。
修正方案

如果要实现「判断用户输入是否为合法整数」的需求,可参考以下修正代码:

#include <iostream>
#include <unistd.h>
#include <cctype>
#include <string>

using namespace std;

int main()
{
    string input;
    bool is_valid_number = true;
    
    cout << "Enter a number \n";
    cout << "input: ";
    cin >> input;

    // 逐字符判断所有内容都是数字
    for (char c : input) {
        if (!isdigit(static_cast<unsigned char>(c))) {
            is_valid_number = false;
            break;
        }
    }

    if (is_valid_number) {
        // 转成整数输出
        int num = stoi(input);
        cout << "Your number is: " << num;
    } else { 
        cout << "This is not a number \n";
    }
    
    //wait for ten seconds
    usleep(10000000);
    return 0;
}

补充:如果需要支持负数输入,可额外增加判断逻辑:第一位字符为'-'且字符串长度大于1时,跳过第一位的数字校验即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 23:27:03