How to make sure strtol () has returned successfully?

according documentation:

If successful, the function returns the converted integer as long int value. If a valid conversion cannot be performed, a null value is returned. If the correct value is out of range, the return values ​​are LONG_MAX or LONG_MIN, and the errno global variable is set to ERANGE.

Consider strtol(str, (char**)NULL, 10); , if str is "0\0" , how do you know if the function worked or just converted the string with the number "0" ?

+6
source share
3 answers

You need to pass the real address of the pointer if you want to check the error, so you can distinguish between 0 values ​​arising from "0" and similar values ​​of 0 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 
+11
source

You can either check errno or pass a non-NULL value for the second argument and compare its resulting value with str , for example:

 char * endptr; long result = strtol(str, &endptr, 10); if (endptr > str) { // Use result... } 
+1
source

IMHO, I prefer from sscanf() to atoi() or strtol() . The main reason is that you cannot reliably check the error status on some platforms (e.g. Windows) unless you use sscanf() (which returns 1 if you succeed, and 0 if you fail).

+1
source

Source: https://habr.com/ru/post/919415/


All Articles