Vaughan Hilts
Vaughan Hilts

Reputation: 2879

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

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?

Upvotes: 4

Views: 972

Answers (3)

tab
tab

Reputation: 903

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.

Upvotes: 6

OnlineCop
OnlineCop

Reputation: 4069

You can check for the presence of errno as indicated in the example here on CppReference.

Upvotes: 0

Eric
Eric

Reputation: 843

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?

Upvotes: 1

Related Questions