Using isdigit() in C/C++

Filed Under: C Programming
Isdigit C

In this article, we’ll take a look at using the isdigit() function in C/C++. This is a very simple way to check if any value is a digit or not. Let’s look at how to use this function, using some simple examples.


Basic Syntax of isdigit() in C/C++

This function takes a characer value val and returns 0 or 1, if the value is a numerical digit.

This is defined in the <ctypes.h> header file, so we must also include this file.

#include <ctypes.h>

int isdigit(char value);

The value must be of such a form that it can be converted to an unsigned char, such as a positive integer / ASCII character.

But note that integers will not be considered digits, since only their ascii equivalents are considered.

Using isdigit() in C++

While you can simply copy and paste the C code to C++ too, the C++ standard library already has the implementation of isdigit()!

This make our lives much more simpler, as we can directly use it, from the std namespace:

std::isdigit(char value);

This also returns a bool value instead, but this is equivalent to the integer values 0 and 1, returned by the C version!


Using isdigit() in C/C++

Let’s now see some examples to check if a value is a digit or not.

We’ll take up a few integer numbers and some characters too, and apply isdigit() on them.

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

int main() {
    int a = 9;
    int b = 10;
    int c = 49;
    char d = 'a';
    char e = '0';

    printf("Is %d a digit?\n", a);
    if (isdigit(a)) printf("Yes\n"); else printf("No\n");
    
    printf("Is %d a digit?\n", b);
    if (isdigit(b)) printf("Yes\n"); else printf("No\n");
    
    printf("Is %d a digit?\n", c);
    if (isdigit(c)) printf("Yes\n"); else printf("No\n");
    
    printf("Is %c a digit?\n", d);
    if (isdigit(d)) printf("Yes\n"); else printf("No\n");
    
    printf("Is %c a digit?\n", e);
    if (isdigit(e)) printf("Yes\n"); else printf("No\n");
    return 0;
}

Output

Is 9 a digit?
No
Is 10 a digit?
No
Is 49 a digit?
Yes
Is a a digit?
No
Is 0 a digit?
Yes

As you can observe, the integers 9 and 10 were not considered digits. But the integer 49 has an ASCII character of ‘0’, and this is a digit!

This is exactly the same as '0', and therefore, this character is also a digit, according to isdigit(char)!


Conclusion

In this article, we learned about using the isdigit() function in C/C++. This made us easily check if any character is a digit or not!

You can look at more tutorials on C programming here. Until next time!

References


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages