How to use strtoul
to parse string where zero may be valid?
Any value returned from strtoul()
may be from an expected string input or from other not so expected strings. Further tests are useful.
The following strings all return 0 from strtoul()
- OK
"0"
, "-0"
, "+0"
- Not OK
""
, "abc"
- Usually considered OK:
" 0"
- OK or not OK depending on goals:
"0xyz"
, "0 "
, "0.0"
strtoul()
has the various detection modes.
int base = 10;
char *endptr; // Store the location where conversion stopped
errno = 0;
unsigned long y = strtoul(s, &endptr, base);
if (s == endptr) puts("No conversion"); // "", "abc"
else if (errno == ERANGE) puts("Overflow");
else if (*endptr) puts("Extra text after the number"); // "0xyz", "0 ", "0.0"
else puts("Mostly successful");
What is not yet detected.
Negative input. strtoul()
effectively wraps around such that strtoul("-1", 0, 10) == ULONG_MAX)
. This issue is often missed in cursory documentation review.
Leading white space allowed. This may or may not be desired.
To also detect negative values:
// find sign
while (isspace((unsigned char) *s)) {
s++;
}
char sign = *s;
int base = 10;
char *endptr; // Store the location where conversion stopped
errno = 0;
unsigned long y = strtoul(s, &endptr, base);
if (s == endptr) puts("No conversiosn");
else if (errno == ERANGE) puts("Overflow");
else if (*endptr) puts("Extra text after the number");
else if (sign == '-' && y != 0) puts("Negative value");
else puts("Successful");
endptr
if it points to the begining? – Boweasd123
. You may also check if the first character of the string is a digit or no (if the string is not empty). All in all, Sourav Ghosh's answer seems more extensive. – Obsequies