A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
isdigit returns nonzero if the character is a decimal digit: '0' through '9'. It returns zero for letters, punctuation, and everything else. It does not recognize hexadecimal digits like 'A' or 'f'. For that, use isxdigit. The most common use is validating numeric input before calling atoi or strtol, and parsing numbers character by character from a stream.
#include <stdio.h>#include <ctype.h>int parse_leading_int(const char *s) {int result = 0;while (isdigit((unsigned char)*s)) {result = result * 10 + (*s - '0');s++;}return result;}int main(void) {printf("parse \"42abc\": %d\n", parse_leading_int("42abc"));printf("parse \"100xyz\": %d\n", parse_leading_int("100xyz"));printf("parse \"abc\": %d\n", parse_leading_int("abc"));const char *test = "a1b2c3";printf("\nDigits in \"%s\": ", test);for (const char *p = test; *p; p++) {if (isdigit((unsigned char)*p)) {printf("%c ", *p);}}printf("\n");return 0;}
The parse function accumulates digits until it hits a non-digit. The expression *s - '0' converts the ASCII character to its numeric value. '0' is ASCII 48, '1' is 49, so '1' - '0' = 1. This arithmetic only works because the C standard guarantees that the digit characters are contiguous. It does not guarantee that for letters.
isdigit is the gatekeeper for numeric parsing. Validate before you convert. Extract digits from mixed input. Build parsers that stop at the right boundary. Next: isalnum, which combines isalpha and isdigit in one test.
Finish the lesson once you have worked through the material. This awards ★ 10 XP.