Miscellaneous Library Functions
The last chapter is a toolbox: small standard-library functions that convert text to numbers, classify characters, change case, and end a program cleanly.
In plain English
This chapter is a toolbox of small helpers, like a ruler, a converter, and a label maker.
Numeric conversions
atoi converts a string to int, atol to long, and atof to double. They skip leading whitespace and stop at the first character that cannot be part of the number. They cannot report overflow or distinguish "0" from invalid input, so use strtol or strtod when you need robust error checking.
int n = atoi("42");
long big = atol("123456");
double price = atof("19.95");
printf("%d %ld %.2f\n", n, big, price);Character classification and case conversion
ctype.h provides isalpha, isdigit, isalnum, isspace, and friends. They return non-zero for true and zero for false. toupper and tolower convert a single character when the conversion is defined; otherwise they return the character unchanged. These functions expect an unsigned char value or EOF, so cast when working with plain char.
char c = 'a';
if (isalpha((unsigned char)c)) {
printf("%c\n", toupper((unsigned char)c)); /* A */
}
if (isdigit((unsigned char)'7')) {
printf("digit\n");
}Program termination with exit
exit(status) ends the program immediately. A status of 0 or EXIT_SUCCESS reports success; EXIT_FAILURE reports failure. Returning from main is equivalent to calling exit with the returned value. Registered atexit handlers run during exit, and open streams are flushed, but local variables are not unwound like exceptions in other languages.
#include <stdlib.h>
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", argv[0]);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);Key takeaways
- atoi/atol/atof convert strings but cannot report overflow.
- isdigit, isalpha, and isalnum return non-zero for true.
- toupper/tolower convert one character at a time.
- exit ends the program and flushes streams.
- EXIT_SUCCESS and EXIT_FAILURE are the portable status values.
Common pitfalls
- Using atoi on untrusted input without checking for errors.
- Passing a negative char to ctype functions without casting to unsigned char.
- Assuming exit runs destructors or unwinds the stack.
Key focus
- Know the return conventions of ctype functions.
- Expect questions on atoi behavior with non-numeric input.
Quick check
1. What does atoi("12abc") return?
2. Which function tests whether a character is a digit?