according documentation:
On success, the function returns the converted integral number as a long int value. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, LONG_MAX or LONG_MIN is returned, and the global variable errno is set to ERANGE.
Consider strtol(str, (char**)NULL, 10);
if str
is "0\0"
how to know if the function failed or only has converted the string with "0"
number?
To determine if 0 is valid, you must also look at the value errno was set do during the call (if it was set). Specifically, if errno != 0 and the value returned by strtol is 0 , then the value returned by strtol is INVALID.
Returns. The strtol function returns the long integer representation of a string. The strtol function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.
If an underflow occurs, strtol() returns LONG_MIN. If an overflow occurs, strtol() returns LONG_MAX. In both cases, errno is set to ERANGE. Precisely the same holds for strtoll() (with LLONG_MIN and LLONG_MAX instead of LONG_MIN and LONG_MAX).
C Programming/stdlib. h/strtol strtol is a function in the C programming language that converts a string into a long integer. strtol stands for string to long. It is included in the C standard library header file stdlib.
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
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