The isdigit() function in C++ is used to check if a given character is a number or not.
To use the isdigit() function, include the following library:
#include <cctype>
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.
isdigit() function returns a non-zero value if c is a digit.isdigit() function returns 0 if c is not a digit.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;}
Two characters c1 and c2 are declared in line 7-8.
c1 is not a digit and c2 is a digit.
isdigit() function is used in line 10 to check whether c1 is a digit. The isdigit() function returns 0 which means that c1 is not a digit.isdigit() function is used in line 11 to check whether c2 is a digit. The isdigit() function returns a non-zero value which means that c2 is a digit.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;}
str is declared that contains both digits and non-digits characters.withoutDigits is declared that will contain the non-digit characters of str.digitCount is declared that will contain the count of the number of digit characters of str.str such that if a character is a non-digit then copy the character in withoutDigits and if a character is a digit then add one to digitCount.Free Resources