Number Parsing in Cilk
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:
Note that the exact output format may vary slightly depending on your system and compiler settings.