Home > Backend Development > C++ > How Can I Properly Handle Errors When Using strtol in C and C ?

How Can I Properly Handle Errors When Using strtol in C and C ?

Barbara Streisand
Release: 2024-12-25 15:35:09
Original
866 people have browsed it

How Can I Properly Handle Errors When Using strtol in C and C  ?

Proper Usage of strtol with Error Handling

The following C or C program converts strings to long integers, relying on the fact that strtol returns NULL for successful conversions. However, when given the value 55, it fails with the following message:

./convertToLong 55
Could not convert 55 to long and leftover string is: 55 as long is 55
Copy after login

This article explores how to correctly detect errors in strtol and address the issue in the given program.

Error Handling in strtol

The official specification for strtol (and related functions like strtoll) states that:

  • It splits the input string into three parts: whitespace, subject (integer), and unrecognized characters.
  • If the subject is empty or invalid, no conversion occurs, and endptr points to the beginning of the input string.
  • If the converted value is outside the representable range, it returns the appropriate minimum or maximum value (e.g., LONG_MIN or LONG_MAX), and errno is set to ERANGE.

Correcting the Program

In C, errors from strtol can be detected by setting errno to zero before calling the function. The modified parseLong function below follows this approach:

static long parseLong(const char *str)
{
    errno = 0;
    char *temp;
    long val = strtol(str, &temp, 0);

    if (temp == str || *temp != '<pre class="brush:php;toolbar:false">bool parseLong(const char *str, long *val)
{
    char *temp;
    bool rc = true;
    errno = 0;
    *val = strtol(str, &amp;temp, 0);

    if (temp == str || *temp != '' ||
        ((*val == LONG_MIN || *val == LONG_MAX) &amp;&amp; errno == ERANGE))
        rc = false;

    return rc;
}
Copy after login
' || ((val == LONG_MIN || val == LONG_MAX) && errno == ERANGE)) fprintf(stderr, "Could not convert '%s' to long and leftover string is: '%s'\n", str, temp); // cerr << "Could not convert '" << str << "' to long and leftover string is '" // << temp << "'\n"; return val; }
  • If the input is empty, invalid, or has trailing characters, it prints an error to stderr and returns 0 or LONG_MIN/LONG_MAX if the error was due to range overflow.
  • If there were no errors, it returns the converted value.

In C , a more flexible approach is to return a success/failure indicator and provide a separate function for extracting the converted value:

Conclusion

With these modifications, the parseLong function correctly handles errors from strtol, allowing applications to determine the success or failure of conversions and handle errors appropriately.

The above is the detailed content of How Can I Properly Handle Errors When Using strtol in C and C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template