Number Parsing in C
Here’s the translation of the number parsing example from Go to C, formatted in Markdown suitable for Hugo:
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:
Next, we’ll look at another common parsing task: URLs.