Home >Backend Development >C++ >How Can I Reliably Detect Errors When Converting Strings to Long Integers Using strtol in C?
Detecting Errors in String to Long Conversion Using strtol
In C programming, the strtol function is commonly used to convert a string representation of a long integer to its numerical value. However, using strtol alone may not always provide sufficient error handling.
Problem:
The provided code demonstrates a scenario where the program correctly converts a string to a long integer, but also prints an error message stating "Could not convert" despite a successful conversion. This is because the program assumes that if strtol successfully converts the string, the second parameter (indicating a leftover string) should be NULL. However, certain conditions can lead to non-NULL leftover strings even with a successful conversion.
Solution:
To accurately detect errors from strtol, consider the following improvements:
Revised Function:
bool parseLong(const char *str, long *val) { char *temp; bool rc = true; errno = 0; *val = strtol(str, &temp, 0); if (temp == str || *temp != '<pre class="brush:php;toolbar:false">if (parseLong(str, &value)) // Conversion successful else // Handle error' || ((*val == LONG_MIN || *val == LONG_MAX) && errno == ERANGE)) rc = false; return rc; }
Usage:
This revised function returns a boolean to indicate if the conversion was successful or not. You can use it as follows:
Additional Notes:
The above is the detailed content of How Can I Reliably Detect Errors When Converting Strings to Long Integers Using strtol in C?. For more information, please follow other related articles on the PHP Chinese website!