C++ 中的 isdigit()
函数用于检查给定字符是否为数字。它定义在 cctype 头文件中。
示例
#include <iostream>
using namespace std;
int main() {
// checks if '9' is a digit
cout << isdigit('9');
return 0;
}
// Output: 1
isdigit() 语法
isdigit()
函数的语法是
isdigit(int ch);
这里,ch 是我们要检查的字符。
isdigit() 参数
isdigit()
函数接受以下参数
- ch - 要检查的字符,强制转换为
int
类型或EOF
isdigit() 返回值
isdigit()
函数返回
- 如果 ch 是数字,则返回非零整数值(
true
) - 如果 ch 不是数字,则返回整数零(
false
)
isdigit() 原型
isdigit()
在 cctype 头文件中定义的原型是
int isdigit(int ch);
正如我们所看到的,字符参数 ch 实际上是 int
类型。这意味着 isdigit()
函数会检查字符的ASCII值。
isdigit() 未定义行为
如果发生以下情况,isdigit()
的行为是未定义的
- ch的值无法表示为unsigned char,或者
- ch的值不等于
EOF
。
示例:C++ isdigit()
#include <cctype>
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "hj;pq910js4";
int check;
cout << "The digit in the string are:" << endl;
for (int i = 0; i < strlen(str); i++) {
// check if str[i] is a digit
check = isdigit(str[i]);
if (check)
cout << str[i] << endl;
}
return 0;
}
输出
The digit in the string are: 9 1 0 4
这里,我们创建了一个 C 字符串 str。然后,我们使用 for 循环 仅打印 字符串 中的数字。循环从 i = 0
到 i = strlen(str) - 1
运行。
for (int i = 0; i < strlen(str); i++) {
...
}
换句话说,循环遍历整个字符串,因为 strlen() 给出了 str 的长度。
在循环的每次迭代中,我们使用 isdigit()
函数来检查字符串元素 str[i]
是否是数字。结果存储在 check 变量中。
check = isdigit(str[i]);
如果 check 返回非零值,则打印字符串元素。
if (check)
cout << str[i] << endl;