- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - isdigit() 函数
C 的ctype 库 isdigit() 函数检查传递的字符是否为十进制数字字符。此函数在各种场景中很有用,例如解析用户的数字输入或处理需要数字验证的数据。
十进制数字是(数字) - 0 1 2 3 4 5 6 7 8 9。
语法
以下是 isdigit() 函数的 C 库语法 -
int isdigit(int c);
参数
此函数接受一个参数 -
c - 这是要检查的字符,作为整数传递。这是字符的 ASCII 值。
返回值
以下是返回值 -
- 如果字符 c 是十进制数字(即 '0' 到 '9'),则函数返回非零值(true)。
- 如果字符 c 不是十进制数字,则返回 0(false)。
示例 1:简单的数字检查
主函数检查传递给它的数字/字符是否为数字/非数字。
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = '5';
if (isdigit(ch)) {
printf("'%c' is a digit.\n", ch);
} else {
printf("'%c' is not a digit.\n", ch);
}
return 0;
}
输出
以上代码产生以下结果 -
'5' is a digit.
示例 2:字符串中的数字检查
以下代码演示了在处理字符串和识别其中数字时使用 isdigit 的方法。
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Hello123";
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) {
printf("'%c' is a digit.\n", str[i]);
} else {
printf("'%c' is not a digit.\n", str[i]);
}
}
return 0;
}
输出
执行以上代码后,我们得到以下结果 -
'H' is not a digit. 'e' is not a digit. 'l' is not a digit. 'l' is not a digit. 'o' is not a digit. '1' is a digit. '2' is a digit. '3' is a digit.
广告