Number Parsing in Cilk

#include <cilk/cilk.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    // With atof, we can parse floating-point numbers
    float f = atof("1.234");
    printf("%f\n", f);

    // For parsing integers, we can use atoi or strtol
    int i = atoi("123");
    printf("%d\n", i);

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

    // For unsigned integers, we can use strtoul
    unsigned long u = strtoul("789", NULL, 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 on bad input, so we need to check errno
    int result = atoi("wat");
    if (result == 0 && errno != 0) {
        perror("Error parsing integer");
    }

    return 0;
}

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

The standard C library provides several functions for number parsing, which are available in Cilk.

With atof, we can parse floating-point numbers. This function returns a double, which we’re casting to a float in this example.

For parsing integers, we can use atoi or strtol. The atoi function is simpler but less flexible, while strtol allows specifying the base and detecting errors.

strtol can recognize hex-formatted numbers when we pass 0 as the base, allowing it to infer the base from the string prefix.

For unsigned integers, we can use strtoul, which works similarly to strtol but returns an unsigned long.

atoi is a convenience function for basic base-10 integer parsing.

Unlike the Go version, C functions like atoi and atof don’t return an error value. Instead, they return 0 for invalid input, which can be ambiguous if 0 is a valid result. To detect errors, you need to check the global errno variable after the call.

To run this program, save it as number_parsing.c, compile it with a Cilk-compatible compiler, and then run the resulting executable:

$ clang -fcilkplus number_parsing.c -o number_parsing
$ ./number_parsing
1.234000
123
456
789
135
Error parsing integer: Invalid argument

Note that the exact output format may vary slightly depending on your system and compiler settings.