Number Parsing in C

Here’s the translation of the number parsing example from Go to C, formatted in Markdown suitable for Hugo:

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

int main() {
    // With strtod, we parse a floating-point number
    char *end;
    double f = strtod("1.234", &end);
    printf("%f\n", f);

    // For strtol, the 0 means infer the base from the string
    long i = strtol("123", &end, 0);
    printf("%ld\n", i);

    // strtol will recognize hex-formatted numbers
    long d = strtol("0x1c8", &end, 0);
    printf("%ld\n", d);

    // strtoul is available for unsigned long
    unsigned long u = strtoul("789", &end, 0);
    printf("%lu\n", u);

    // atoi is a convenience function for basic base-10 int parsing
    int k = atoi("135");
    printf("%d\n", k);

    // Parse functions return 0 and set errno on bad input
    errno = 0;
    long e = strtol("wat", &end, 10);
    if (errno != 0) {
        perror("Error");
    }

    return 0;
}

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in C.

The standard C library provides several functions for number parsing in <stdlib.h>.

With strtod, we parse a floating-point number. The second argument is a pointer to a char pointer where the address of the first invalid character will be stored.

For strtol, the third argument specifies the base. Using 0 means to infer the base from the string (10 for decimal, 16 for hexadecimal if it starts with “0x”, and 8 for octal if it starts with “0”).

strtol will recognize hex-formatted numbers when the base is set to 0 or 16.

strtoul is available for parsing unsigned long integers.

atoi is a convenience function for basic base-10 int parsing. It’s equivalent to (int)strtol(nptr, NULL, 10).

Parse functions in C typically return 0 and set errno on bad input. It’s a good practice to check errno after calling these functions to ensure the parsing was successful.

To compile and run this program:

$ gcc number_parsing.c -o number_parsing
$ ./number_parsing
1.234000
123
456
789
135
Error: Invalid argument

Next, we’ll look at another common parsing task: URLs.