在 C++ 中,isdigit() 是一个用于判断字符是否为十进制数字(即 '0''9')的标准函数。它定义在头文件 <cctype> 中,其原型如下:([blog.csdn.net][1], [geeksforgeeks.org][2])

int isdigit(int ch);

🧠 函数说明


✅ 示例代码

以下是一个使用 isdigit() 函数的示例,判断输入的字符是否为数字:([blog.csdn.net][1])

#include <iostream>
#include <cctype>

int main() {
    char ch = '5';

    if (std::isdigit(static_cast<unsigned char>(ch))) {
        std::cout << ch << " 是数字字符。" << std::endl;
    } else {
        std::cout << ch << " 不是数字字符。" << std::endl;
    }

    return 0;
}

输出:

5 是数字字符。

🔄 应用示例:统计字符串中的数字字符个数

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
    std::string str = "C++20 于 2020 年发布。";
    int count = std::count_if(str.begin(), str.end(), [](unsigned char c) {
        return std::isdigit(c);
    });

    std::cout << "字符串中包含 " << count << " 个数字字符。" << std::endl;
    return 0;
}

输出:

字符串中包含 4 个数字字符。

⚠️ 常见注意事项