This might seem super obvious but strtol provides a response to the parsed integer -- but it's 0 on fail. What if the integer I parsed is 0?
errno
is only guaranteed to be set in the case of over/underflow (to ERANGE
). For other errors you must check the value of endptr
. Quoting C89:
long int strtol(const char *nptr, char **endptr, int base);
If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
Normally endptr is set to point to the next character in the input string after the last character converted, so if it's the equal to the beginning of the string, you can be sure no conversion has been performed. For example,
char *nptr = "not a number", *endptr;
long n = strtol(nptr, &endptr, 10);
assert(nptr != endptr); //false
POSIX contains a handy extension which also sets errno
to EINVAL
in this case, but this is nonstandard.
According to man strtol
:
If no conversion could be performed, 0 is returned and the global variable errno is set to EINVAL (the last feature is not portable across all platforms).
Is that not the case on you platform? If so, what platform are you on?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With