Checking for digits with isdigit and isxdigit
What you'll learn: How to identify numeric characters and hexadecimal values using specialized functions from the C standard library.
The character gatekeepers
When you receive input from a user, it arrives as a char, even if they typed a number. If you want to know whether a character is a digit like '5' rather than a letter like 'A', you could check if the character falls between '0' and '9' manually. However, the <ctype.h> library provides a cleaner, more readable way to do this using isdigit.
Think of isdigit as a security guard at a gate. It looks at a single character and asks: "Are you a standard base-10 digit?" If the character is anywhere from '0' to '9', the function returns a non-zero value (true). Otherwise, it returns zero (false).
Leveling up to Hexadecimal
Sometimes, standard digits aren't enough. In programming, we frequently use hexadecimal (base-16) to represent memory addresses or colors. Hexadecimal includes the digits 0-9 but adds the letters A through F.
The isxdigit function is the specialized version of our guard. It checks if a character is a valid "hex" digit. It returns true for:
- Standard digits:
0 1 2 3 4 5 6 7 8 9 - Uppercase hex letters:
A B C D E F - Lowercase hex letters:
a b c d e f
Seeing it in action
Here is how you use these functions in a real program. Remember to include <ctype.h> at the top of your file.
#include <stdio.h>
#include <ctype.h>
int main() {
char test1 = '7';
char test2 = 'f';
char test3 = 'Q';
// Checking for standard digits
if (isdigit(test1)) {
printf("'%c' is a decimal digit.\n", test1);
}
// Checking for hex digits
if (isxdigit(test2)) {
printf("'%c' is a valid hex digit.\n", test2);
}
// This will fail both checks
if (!isxdigit(test3)) {
printf("'%c' is not a digit or a hex letter.\n", test3);
}
return 0;
}
Using these functions makes your code more "self-documenting." Instead of writing complex math logic to check character ranges, you are telling anyone reading your code exactly what you are looking for in plain English.
Key takeaway
Use isdigit to find numbers 0-9, and isxdigit when you need to include the letters A-F for hexadecimal values.