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
endpoints at the first character not consumed.errno == ERANGEmarks an out-of-range value.- A value equal to the whole string means a clean parse.
Keywords and builtins used here
NULLcharconstdoubleifintlongparse_doubleparse_intreturn
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.
Step 2 of 3 in Splitting & parsing, step 9 of 13 in Strings & text.