according documentation:
On success, the function returns the converted integral number as a long int value. If no valid conversion could be perfor
You need to pass a real pointer address if you want error checking, so you can distinguish 0 values arising from "0"
and similar from 0 values arising from "pqr"
:
char *endptr;
errno = 0;
long result = strtol(str, &endptr, 10);
if (endptr == str)
{
// nothing parsed from the string, handle errors or exit
}
if ((result == LONG_MAX || result == LONG_MIN) && errno == ERANGE)
{
// out of range, handle or exit
}
// all went fine, go on
Since the accepted answer is not actually a correct way to check for failure.
You should not check for errors by examining the return value of strtol, because the string might be a valid representation of 0l, LONG_MAX, or LONG_MIN. Instead, check whether tailptr points to what you expect after the number (e.g. '\0' if the string should end after the number). You also need to clear errno before the call and check it afterward, in case there was overflow.
IMHO, I prefer sscanf()
to atoi()
or strtol()
. The main reason is that you cannot reliably check for error status on some platforms (i.e. Windows) unless you use sscanf()
(which returns 1
if you succeed, and 0
if you fail).
You can either check the errno
or pass a non-NULL value for the second argument and compare its resulting value to str
, like:
char * endptr;
long result = strtol(str, &endptr, 10);
if (endptr > str)
{
// Use result...
}