typestar

Parsing numbers properly in C

strtol reports where it stopped and sets errno on overflow — atoi does neither.

#include <errno.h>
#include <stdlib.h>

int parse_int(const char *text, long *out) {
    if (text == NULL || *text == '\0') {
        return 0;
    }
    errno = 0;
    char *end = NULL;
    long value = strtol(text, &end, 10);

    if (end == text || *end != '\0') {
        return 0;
    }
    if (errno == ERANGE) {
        return 0;
    }
    *out = value;
    return 1;
}

double parse_double(const char *text, int *ok) {
    char *end = NULL;
    double value = strtod(text, &end);
    *ok = (end != text && *end == '\0');
    return value;
}

How it works

  1. end points at the first character not consumed.
  2. errno == ERANGE marks an out-of-range value.
  3. A value equal to the whole string means a clean parse.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
464
Tokens
158
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 95 seconds.

Type this snippet

Step 2 of 3 in Splitting & parsing, step 9 of 13 in Strings & text.

← Previous Next →