std::isdigit
来自cppreference.com
| 在标头 <cctype> 定义
|
||
| |
||
检查给定的字符是否是 10 个十进制数位(0123456789)之一。
若 ch 的值不能表示为 unsigned char 且不等于 EOF,则行为未定义。
参数
| ch | - | 要分类的字符 |
返回值
若字符为数字字符则为非零值,否则为零。
注解
isdigit 和 isxdigit 是仅有的不受当前安装的 C 本地环境影响的标准窄字符分类函数。尽管某些实现(例如 Microsoft 在 1252 代码页)可能分类另外的单字节字符为数字。
同所有其他来自 <cctype> 的函数,若实参值既不能表示为 unsigned char 又不等于 EOF 则 std::isdigit 的行为未定义。为了以单纯的 char(或 signed char)安全使用此函数,首先要将实参转换为 unsigned char:
bool my_isdigit(char ch)
{
return std::isdigit(static_cast<unsigned char>(ch));
}
类似地,迭代器的值类型为 char 或 signed char 时,不应直接将它们用于标准算法。而是要首先转换值为 unsigned char:
int count_digits(const std::string& s)
{
return std::count_if(s.begin(), s.end(),
// static_cast<int(*)(int)>(std::isdigit) // 错误
// [](int c){ return std::isdigit(c); } // 错误
// [](char c){ return std::isdigit(c); } // 错误
[](unsigned char c){ return std::isdigit(c); } // 正确
);
}
示例
运行此代码
#include <cctype>
#include <climits>
#include <iostream>
int main(void)
{
for (int i = 0; i <= UCHAR_MAX; ++i)
if (std::isdigit(i))
std::cout << static_cast<unsigned char>(i);
std::cout << '\n';
}
输出:
0123456789
参阅
| 检查字符是否被本地环境分类为数字 (函数模板) | |