Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse an integer but keep "0" as a valid value using strtol?

Tags:

c

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?

like image 490
Vaughan Hilts Avatar asked Mar 21 '23 23:03

Vaughan Hilts


2 Answers

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.

like image 142
tab Avatar answered Mar 23 '23 13:03

tab


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?

like image 24
Eric Avatar answered Mar 23 '23 13:03

Eric