What is isdigit() in C++?
The isdigit() function in C++ is used to check if a given character is a number or not.
Library
To use the isdigit() function, include the following library:
#include <cctype>
Declaration
The isdigit() function is declared as follows:
int isdigit(int c);
c: The ASCII value of the character that is to be checked whether it is a digit.
Note: If
cis not an unsigned char or EOF, the behavior of theisdigit()function is undefined.
Return value
- The
isdigit()function returns a non-zero value ifcis a digit. - The
isdigit()function returns 0 ifcis not a digit.
Examples
Example 1
Consider the code snippet below, which demonstrates the use of the isdigit() function:
#include <cctype>#include <iostream>using namespace std;int main(){char c1 = 'a';char c2 = '8';cout<<c1<<" is digit: "<<isdigit(c1)<<endl;cout<<c2<<" is digit: "<<isdigit(c2)<<endl;return 0;}
Explanation
Two characters c1 and c2 are declared in line 7-8.
c1 is not a digit and c2 is a digit.
- line 10: The
isdigit()function is used in line 10 to check whetherc1is a digit. Theisdigit()function returns 0 which means thatc1is not a digit. - line 11: The
isdigit()function is used in line 11 to check whetherc2is a digit. Theisdigit()function returns a non-zero value which means thatc2is a digit.
Example 2
Consider the code snippet below, which uses the isdigit() function to remove the digits from other characters in a string:
#include <cctype>#include <cstring>#include <iostream>using namespace std;int main(){char str[] = "H5el6lo7 8w7o0rld!!123";int len = strlen(str);char withoutDigits[len];int digitCount = 0;int ind = 0 ;for(int i = 0; i < len; i++){if( isdigit(str[i])==0 ){withoutDigits[ind] = str[i];ind++;}else{digitCount++;}}cout<<"string = "<<str<<endl;cout<<"string without digits = "<<withoutDigits<<endl;cout<<"number of digits in string = "<<digitCount<<endl;return 0;}
Explanation
- line 8: A string
stris declared that contains both digits and non-digits characters. - line 10: A string
withoutDigitsis declared that will contain the non-digit characters ofstr. - line 11: A variable
digitCountis declared that will contain the count of the number of digit characters ofstr. - line 14-17: Loop over the characters of
strsuch that if a character is a non-digit then copy the character inwithoutDigitsand if a character is a digit then add one todigitCount.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved