Reading history

String to Number Conversion in C: atoi vs strtol, sscanf, snprintf

5 min read 1 views

Convert strings to numbers in C safely: atoi and atof limitations, strtol and strtod with end pointers, bases, errno overflow checks, sscanf and snprintf.

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 atoi is risky
  • Using strtol and its end pointer
  • Parsing hexadecimal, octal and binary text
  • Detecting overflow with errno and ERANGE
  • Reading fields with sscanf and formatting with snprintf

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
  • atoi converts 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) sets end to the first character it did not use:
    • end == text means 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.
  • strtol skips leading spaces and accepts a sign.
  • Base 0 detects the prefix automatically: 0x1F is 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_int combines every check: digits present, nothing left over, no ERANGE overflow and within the range of int. Setting errno = 0 first 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).
  • sscanf reads several fields from a string using a format, like scanf on text. Always check that its return value equals the number of fields you expected.
  • snprintf goes the other way, number to text, and never writes past the buffer size. It returns the length the full text needed, so a result of sizeof buf or more means it was cut short.

Conversion Functions

FunctionConverts toReports errors?
atoi, atolint, longNo
atofdoubleNo
strtol, strtolllong, long longYes (end pointer, errno)
strtoulunsigned longYes
strtod, strtofdouble, floatYes
sscanfSeveral fieldsPartly (count of fields read)
snprintfNumber to stringReturns needed length

Common Mistakes

  1. Using atoi on untrusted input.
  2. Not resetting errno before strtol, then reading a stale error.
  3. Ignoring the end pointer, so “12abc” is accepted as 12.
  4. Using sprintf instead of snprintf, 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

  • atoi and atof are quick but cannot report errors.
  • strtol/strtod with the end pointer and errno validate input fully.
  • Base 0 detects hex and octal prefixes.
  • Use sscanf to read fields and snprintf to format safely.

Next: Bit Fields in C.

Lessons are also marked complete when you click Next.

Leave a Reply

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