User input, files and command-line arguments all arrive as text, but calculations need numbers. C offers two families of conversion functions: the quick atoi/atof, which cannot report errors, and the robust strtol/strtod, which tell you exactly where parsing stopped and whether the value fitted. This lesson compares them, builds a safe integer parser, and shows the reverse direction with snprintf.
In this lesson you will learn
- Why
atoiis risky - Using
strtoland its end pointer - Parsing hexadecimal, octal and binary text
- Detecting overflow with
errnoandERANGE - Reading fields with
sscanfand formatting withsnprintf
atoi vs strtol
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("atoi(\"123\") = %d\n", atoi("123"));
printf("atoi(\"12abc\") = %d\n", atoi("12abc"));
printf("atoi(\"abc\") = %d <- error or real zero? atoi cannot tell\n", atoi("abc"));
printf("atof(\"3.75\") = %.2f\n", atof("3.75"));
const char *inputs[] = {"250", " -42", "99kg", "hello", "0x1F"};
for (int i = 0; i < 5; i++) {
char *end;
long v = strtol(inputs[i], &end, 0); /* base 0: detects 0x and 0 prefixes */
if (end == inputs[i])
printf("%-7s -> no number found\n", inputs[i]);
else if (*end != '\0')
printf("%-7s -> %ld, leftover \"%s\"\n", inputs[i], v, end);
else
printf("%-7s -> %ld\n", inputs[i], v);
}
printf("binary 1011 = %ld\n", strtol("1011", NULL, 2));
return 0;
}
Output
atoi("123") = 123
atoi("12abc") = 12
atoi("abc") = 0 <- error or real zero? atoi cannot tell
atof("3.75") = 3.75
250 -> 250
-42 -> -42
99kg -> 99, leftover "kg"
hello -> no number found
0x1F -> 31
binary 1011 = 11
atoiconverts the leading digits and ignores the rest, so"12abc"gives 12. For"abc"it returns 0, which is indistinguishable from a real zero. On overflow its behaviour is undefined.strtol(text, &end, base)setsendto the first character it did not use:end == textmeans no digits at all;*end != '\0'means there was extra text, like the “kg” in “99kg”;*end == '\0'means the whole string was a number.
strtolskips leading spaces and accepts a sign.- Base 0 detects the prefix automatically:
0x1Fis hexadecimal 31 and a leading 0 means octal. Base 2 parses binary.
A Safe Parser, sscanf and snprintf
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
static int parse_int(const char *s, int *out) {
char *end;
errno = 0;
long v = strtol(s, &end, 10);
if (end == s || *end != '\0') return 0; /* not a whole number */
if (errno == ERANGE || v < INT_MIN || v > INT_MAX) return 0; /* too big */
*out = (int)v;
return 1;
}
int main(void) {
const char *tests[] = {"2026", "-15", "12.5", "", "99999999999999999999"};
for (int i = 0; i < 5; i++) {
int v;
if (parse_int(tests[i], &v)) printf("\"%s\" -> %d\n", tests[i], v);
else printf("\"%s\" -> invalid\n", tests[i]);
}
int day, month, year;
if (sscanf("16/11/2026", "%d/%d/%d", &day, &month, &year) == 3)
printf("day=%d month=%d year=%d\n", day, month, year);
char buf[32];
int len = snprintf(buf, sizeof buf, "%d items at %.2f", 3, 45.5);
printf("\"%s\" (%d chars)\n", buf, len);
return 0;
}
Output
"2026" -> 2026
"-15" -> -15
"12.5" -> invalid
"" -> invalid
"99999999999999999999" -> invalid
day=16 month=11 year=2026
"3 items at 45.50" (16 chars)
parse_intcombines every check: digits present, nothing left over, noERANGEoverflow and within the range ofint. Settingerrno = 0first is required, because successful calls do not reset it.- The function returns success or failure separately from the value, so 0 is never ambiguous. This pattern is the C equivalent of exception handling for parsing (see Error Handling in C).
sscanfreads several fields from a string using a format, likescanfon text. Always check that its return value equals the number of fields you expected.snprintfgoes the other way, number to text, and never writes past the buffer size. It returns the length the full text needed, so a result ofsizeof bufor more means it was cut short.
Conversion Functions
| Function | Converts to | Reports errors? |
|---|---|---|
atoi, atol | int, long | No |
atof | double | No |
strtol, strtoll | long, long long | Yes (end pointer, errno) |
strtoul | unsigned long | Yes |
strtod, strtof | double, float | Yes |
sscanf | Several fields | Partly (count of fields read) |
snprintf | Number to string | Returns needed length |
Common Mistakes
- Using atoi on untrusted input.
- Not resetting errno before
strtol, then reading a stale error. - Ignoring the end pointer, so “12abc” is accepted as 12.
- Using
sprintfinstead ofsnprintf, which can overflow the buffer.
Practice Exercises
Exercise 1. Convert the hexadecimal colour string "FF8800" to its red, green and blue values.
Show answer
long rgb = strtol("FF8800", NULL, 16);
int r = (rgb >> 16) & 0xFF, g = (rgb >> 8) & 0xFF, b = rgb & 0xFF;
printf("%d %d %d\n", r, g, b); /* 255 136 0 */
This also uses bitwise operators.
Exercise 2. Parse "Nadia,78" into a name and a mark with sscanf.
Show answer
char name[20]; int mark;
if (sscanf("Nadia,78", "%19[^,],%d", name, &mark) == 2)
printf("%s scored %d\n", name, mark);
%19[^,] reads up to 19 characters that are not commas, leaving room for the terminator.
Frequently Asked Questions
How do I convert a number to a string in C?
Use snprintf(buf, sizeof buf, "%d", n). The non-standard itoa exists on some compilers but is not portable.
Does strtod depend on the locale?
Yes. In some locales the decimal separator is a comma, so strtod("3.5") might stop at the dot. Programs use the default “C” locale unless they call setlocale.
Summary
atoiandatofare quick but cannot report errors.strtol/strtodwith the end pointer anderrnovalidate input fully.- Base 0 detects hex and octal prefixes.
- Use
sscanfto read fields andsnprintfto format safely.
Next: Bit Fields in C.
