Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make sure that strtol() have returned successfully?

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?

like image 219
Jack Avatar asked Jul 01 '12 05:07

Jack


People also ask

How do you know if strtol failed?

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.

What does strtol return?

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.

What happens if strtol fails?

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).

What library is strtol in C?

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.


1 Answers

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
like image 88
Daniel Fischer Avatar answered Oct 24 '22 11:10

Daniel Fischer