The C ctype library isdigit() function checks if the passed character is a decimal digit character. This function is useful in various scenarios such as parsing numerical input from a user or processing data where digit validation is required.
Decimal digits are (numbers) − 0 1 2 3 4 5 6 7 8 9.
Syntax
Following is the C library syntax of the isdigit() function −
int isdigit(int c);
Parameters
This function accepts a single parameter −
c − This is the character to be checked, passed as an integer.This is an ASCII value of a character.
Return Value
Following is the return value −
- The function returns a non-zero value (true) if the character c is a decimal digit (i.e., '0' through '9').
- It returns 0 (false) if the character c is not a decimal digit.
Example 1: Simple Digit Check
The main function checks if the digits/character passed to it is a digit/ non-digit.
#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;}
Output
The above code produces following result−
'5' is a digit.
Example 2: Digit Check in a String
The below code demonstrates the use of isdigit in processing strings and identifying digits within them.
#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;}
Output
After execution of above code, we get the following result −
'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.
Advertisem*nts