Skip to content

Checked Numeric Conversion

The Course
•
35 min study

After the topic comes the duration, still as text: "25". The tempting tool is atoi, but it cannot report failure. atoi("25x") returns 25 and ignores the junk, atoi("abc") returns 0 with no way to tell that from a real zero, and if the digits describe a number too large for int, the behavior is undefined. A parser built on atoi accepts bad input silently. strtol from <stdlib.h> does the same conversion but tells you everything you need to reject bad text: where it stopped reading, and whether the value fit.

Predict and run

Read the program before pressing Run. Write down its four lines and explain why value keeps 25.

Predict before running C
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int parse(const char *text, int *out) {
    if (*text < '0' || *text > '9') { return 0; }
    errno = 0;
    char *end = NULL;
    long value = strtol(text, &end, 10);
    if (errno == ERANGE || end == text || *end != '\0' || value < 1 || value > 180) { return 0; }
    *out = (int)value;
    return 1;
}

int main(void) {
    int value = 7;
    printf("%d\n", parse("25", &value));
    printf("%d\n", value);
    printf("%d\n", parse("25x", &value));
    printf("%d\n", value);
    return 0;
}
Check your prediction
Text
1
25
0
25

"25" passes every check and is stored. For "25x", strtol converts the prefix 25 and leaves end pointing at x. Because *end is not the terminator, the function rejects the text without writing, so value still holds the 25 from the first call.

What strtol tells you

strtol(text, &end, 10) skips leading whitespace, accepts an optional sign, reads as many base-10 digits as it can, and returns them as a long. Through end it reports the first character it did not use. If there were no digits at all, end equals text and the result is 0. If the number does not fit in long, it returns LONG_MAX or LONG_MIN and sets errno (from <errno.h>) to ERANGE.

Seeing how far it reads makes the checks easier to understand. This program prints the value and how many characters were consumed:

How far strtol reads C
#include <stdio.h>
#include <stdlib.h>

static void show(const char *text) {
    char *end = NULL;
    long value = strtol(text, &end, 10);
    printf("\"%s\": value %ld, used %d chars, rest \"%s\"\n", text, value, (int)(end - text), end);
}

int main(void) {
    show("25");
    show(" 25");
    show("+25");
    show("25x");
    show("abc");
    return 0;
}
Text
"25": value 25, used 2 chars, rest ""
" 25": value 25, used 3 chars, rest ""
"+25": value 25, used 3 chars, rest ""
"25x": value 25, used 2 chars, rest "x"
"abc": value 0, used 0 chars, rest "abc"

The first and fourth lines show the normal cases. The last line shows what "no conversion" looks like: 0 characters used and end left at the start, so the value 0 means nothing. Lines two and three show that strtol accepts more than the analyzer's format, which allows neither a sign nor whitespace inside the number field. That is why the parser checks for a leading digit itself.

Checks in the right order

A converted value is usable only when three separate things are true: the text has the right syntax, the number fits the machine range of long, and it lies in the domain range the contract allows. In code:

  1. *text is a digit. This rejects empty text, signs and leading spaces before strtol sees them.
  2. errno = 0 before the call, then errno == ERANGE after it. Library functions set errno on failure but never clear it on success, so an old ERANGE from an earlier call would otherwise look like a new one.
  3. end != text, so at least one digit was read. With rule 1 this cannot fail, but it keeps the function correct if rule 1 is ever relaxed.
  4. *end == '\0', so nothing follows the digits. This is what rejects 25x.
  5. 1 <= value && value <= 180, the domain range.

Only then is (int)value safe. Converting a long that does not fit in int gives an implementation-defined result, so narrow only after the range check has proven the value fits.

Machine range and domain range are different

A 30-digit number is syntactically perfect and still fails, at step 2: strtol returns LONG_MAX and sets ERANGE. Without the errno check, a value like LONG_MAX would at least be stopped by the domain check here, but a contract with a wider range might accept it. The value 181 is the opposite case: it fits easily in long but is outside the contract. Test both kinds of failure, plus the edges 1 and 180 and their neighbors 0 and 181.

Practice

Exercise

Your turn

Write int parse_pages(const char *text, int *out) that accepts a decimal page count in 1..500. A digit must come first. Trailing whitespace (space, tab, \r, \n) is allowed after the digits, nothing else. Failure leaves *out unchanged. The starter, which starts pages at 7, must print: "120" -> ok, pages 120, "120\n" -> ok, pages 120, "0" -> rejected, pages 120, "501" -> rejected, pages 120, "12 pages" -> rejected, pages 120, "+5" -> rejected, pages 120, "" -> rejected, pages 120, "99999999999999999999" -> rejected, pages 120, "500 " -> ok, pages 500.

Your workspace C
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

/* Write parse_pages here. */

static void show(const char *label, const char *text, int *pages) {
    int ok = parse_pages(text, pages);
    printf("\"%s\" -> %s, pages %d\n", label, ok ? "ok" : "rejected", *pages);
}

int main(void) {
    int pages = 7;
    show("120", "120", &pages);
    show("120\\n", "120\n", &pages);
    show("0", "0", &pages);
    show("501", "501", &pages);
    show("12 pages", "12 pages", &pages);
    show("+5", "+5", &pages);
    show("", "", &pages);
    show("99999999999999999999", "99999999999999999999", &pages);
    show("500 ", "500 ", &pages);
    return 0;
}
Hint 1: the idea

The trailing-whitespace rule changes only step 4. Instead of requiring *end == '\0' immediately, skip whitespace from end first, then require the terminator.

Hint 2: a first step

Start from the lesson's parse with only the range changed to 1..500, and run. Every line is right except "120\n" and "500 ", which are rejected. Print where end points for those two inputs (for example printf("[%s]\n", end);) to see exactly which characters your terminator test still has to let through.

Show one solution
Run the solution C
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int parse_pages(const char *text, int *out) {
    if (*text < '0' || *text > '9') { return 0; }
    errno = 0;
    char *end = NULL;
    long value = strtol(text, &end, 10);
    if (errno == ERANGE || end == text) { return 0; }
    while (*end == ' ' || *end == '\t' || *end == '\r' || *end == '\n') { ++end; }
    if (*end != '\0' || value < 1 || value > 500) { return 0; }
    *out = (int)value;
    return 1;
}

static void show(const char *label, const char *text, int *pages) {
    int ok = parse_pages(text, pages);
    printf("\"%s\" -> %s, pages %d\n", label, ok ? "ok" : "rejected", *pages);
}

int main(void) {
    int pages = 7;
    show("120", "120", &pages);
    show("120\\n", "120\n", &pages);
    show("0", "0", &pages);
    show("501", "501", &pages);
    show("12 pages", "12 pages", &pages);
    show("+5", "+5", &pages);
    show("", "", &pages);
    show("99999999999999999999", "99999999999999999999", &pages);
    show("500 ", "500 ", &pages);
    return 0;
}
Text
"120" -> ok, pages 120
"120\n" -> ok, pages 120
"0" -> rejected, pages 120
"501" -> rejected, pages 120
"12 pages" -> rejected, pages 120
"+5" -> rejected, pages 120
"" -> rejected, pages 120
"99999999999999999999" -> rejected, pages 120
"500 " -> ok, pages 500

Each rejected line leaves 120 in place, which proves no failure path writes. "12 pages" fails because skipping whitespace stops at p, not at the terminator, so trailing whitespace is allowed but a second field is not. The 20-digit input fails on ERANGE, before the domain check. The project's record_parse uses this same sequence after reading the topic. Next, you will read whole lines safely, including lines too long for the buffer.

Was this article helpful?

Your response is saved on this device.