The isdigit()
function in C++ checks if the given character is a digit or not. It is defined in the cctype header file.
Example
#include <iostream>
using namespace std;
int main() {
// checks if '9' is a digit
cout << isdigit('9');
return 0;
}
// Output: 1
isdigit() Syntax
The syntax of the isdigit()
function is:
isdigit(int ch);
Here, ch is the character we want to check.
isdigit() Parameters
The isdigit()
function takes the following parameters:
- ch - the character to check, casted to
int
type orEOF
isdigit() Return Value
The isdigit()
function returns:
- a non-zero integer value (
true
) if ch is a digit - the integer zero (
false
) if ch is not a digit
isdigit() Prototype
The prototype of isdigit()
as defined in the cctype header file is:
int isdigit(int ch);
As we can see, the character parameter ch is actually of int
type. This means that the isdigit()
function checks the ASCII value of the character.
isdigit() Undefined Behavior
The behaviour of isdigit()
is undefined if:
- the value of ch is not representable as
unsigned char
, or - the value of ch is not equal to
EOF
.
Example: C++ isdigit()
#include <cctype>
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "hj;pq910js4";
int check;
cout << "The digit in the string are:" << endl;
for (int i = 0; i < strlen(str); i++) {
// check if str[i] is a digit
check = isdigit(str[i]);
if (check)
cout << str[i] << endl;
}
return 0;
}
Output
The digit in the string are: 9 1 0 4
Here, we have created a C-string str. Then, we printed only the digits in the string using a for
loop. The loop runs from i = 0
to i = strlen(str) - 1
.
for (int i = 0; i < strlen(str); i++) {
...
}
In other words, the loop iterates through the whole string since strlen()
gives the length of str.
In each iteration of the loop, we use the isdigit()
function to check if the string element str[i]
is a digit or not. The result is stored in the check variable.
check = isdigit(str[i]);
If check returns a non-zero value, we print the string element.
if (check)
cout << str[i] << endl;