C isdigit()

isdigit() 函数在 ctype.h 头文件中定义。它用于检查指定的字符是否为十进制数字或数字(0-9)。


int isdigit( int argument ); #where argument will be a character
 

isdigit() 参数

isdigit() 函数接受一个参数,该参数为整数形式,返回值为整数。当传递一个字符时,它会转换为其 ASCII 值对应的整数值。

参数 描述 必需/可选
参数 要检查的字符 必需

isdigit() 返回值

如果给定字符是数字字符,isdigit() 返回非零整数,否则返回零。当传递数字字符时,我们将得到一个不同的非零整数。

输入 返回值
如果参数不是数字字符
非零数字 如果参数是数字字符

Python 中 isdigit() 方法的示例

示例 1:如何在 C 中检查数字字符?


#include <stdio.h>
#include <ctype.h>

int main()
{
    char ch;
    ch='4';
    printf("If numeric character is passed: %d", isdigit(ch));

    ch='+';
    printf("\nIf non-numeric character is passed: %d", isdigit(ch));

    return 0;
}
 

输出


If numeric character is passed: 1
If non-numeric character is passed: 0

示例 2:如何检查字符是否为数字?


#include <stdio.h>
#include <ctype.h>

int main()
{
    char ch;

    printf("Enter any character: ");
    scanf("%c",&ch);

    if (isdigit(ch) == 0)
         printf("The given %c is not a digit.",ch);
    else
         printf("The given %c is a digit.",ch);
    return 0;
}
 

输出


Enter any character: 4
The given 4 is a digit.