"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert Strings to Integers with Error Handling in C++?

How to Convert Strings to Integers with Error Handling in C++?

Published on 2024-11-14
Browse:563

How to Convert Strings to Integers with Error Handling in C  ?

Converting Strings to Integers with Error Handling in C

In programming, it's often necessary to convert strings to integers. While C provides the std::atoi function for this purpose, it doesn't handle conversion errors gracefully. To address this, we seek a solution that allows for error handling, similar to C#'s Int32.TryParse.

Boost's Lexical Cast Function

An efficient approach is to use the lexical_cast function from the Boost library. It supports a variety of data types and can throw an exception if the cast fails. Here's an example:

#include 

int main() {
    std::string s;
    std::cin >> s;

    try {
        int i = boost::lexical_cast(s);

        // ...
    } catch (...) {
        // Handle error
    }
}

Using Standard Library Functions

If Boost is not available, a combination of std::stringstream and >> operator can be used:

#include 
#include 
#include 

int main() {
    std::string s;
    std::cin >> s;

    try {
        std::stringstream ss(s);

        int i;
        if ((ss >> i).fail() || !(ss >> std::ws).eof()) {
            throw std::bad_cast();
        }

        // ...
    } catch (...) {
        // Handle error
    }
}

Faking Boost's Lexical Cast

As a final alternative, a "fake" version of Boost's lexical_cast function can be created:

#include 
#include 
#include 

template 
T lexical_cast(const std::string& s) {
    std::stringstream ss(s);

    T result;
    if ((ss >> result).fail() || !(ss >> std::ws).eof()) {
        throw std::bad_cast();
    }

    return result;
}

int main() {
    std::string s;
    std::cin >> s;

    try {
        int i = lexical_cast(s);

        // ...
    } catch (...) {
        // Handle error
    }
}

No-throw Versions

If a no-throw version is desired, catch the appropriate exceptions and return a boolean indicating success or failure:

template 
bool lexical_cast(const std::string& s, T& t) {
    try {
        t = lexical_cast(s);
        return true;
    } catch (const std::bad_cast& e) {
        return false;
    }
}

int main() {
    std::string s;
    std::cin >> s;

    int i;
    if (!lexical_cast(s, i)) {
        std::cout 
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3