No way to parse integers in C
There are a few ways to attempt to parse a string into a number in the C standard library. They are ALL broken.
Leaving aside the wide character versions, and staying with long
(skipping int, long long or intmax_t, these variants all having
the same problem) there are three ways I can think of:
atol()strtol()/strtoul()sscanf()
They are all broken.
What is the correct behavior, anyway?
I’ll start by claiming a common sense “I know it when I see it”. The
number that I see in the string with my eyeballs must be the numerical
value stored in the appropriate data type. “123” must be turned into
the number 123.
Another criteria is that the WHOLE number must be parsed. It is not OK to stop at the first sign of trouble, and return whatever maybe is right. “123timmy” is not a number, nor is the empty string.
Failing to provide the above must be an error. Or at least as the user of the parser I must have the option to know if it happened.
First up: atol()
| Input | Output |
|---|---|
| 123timmy | 123 |
| 99999999999999999999999999999999 | LONG_MAX |
| timmy | 0 |
| empty string | 0 |
" " |
0 |
No. All Continue reading

