CodingHowTo

Safe stoi/stol: Parsing Ints Without Exceptions

Safe stoi/stol: Parsing Ints Without Exceptions

Introduction

When converting strings to integers using `stoi` or `stol`, it's important to handle potential exceptions. These functions can throw a `std::invalid_argument` if the string doesn't represent a valid integer, and `std::out_of_range` if the value is outside the range of the target type.

Using std::istringstream

A safer approach is to use `std::istringstream`, which allows you to check for parsing errors without exceptions. Here's a simple function that demonstrates this:


    #include <iostream>
    #include <sstream>
    #include <string>

    bool safe_stoi(const std::string& str, int& result) {
        std::istringstream iss(str);
        if (!(iss >> result)) {
            return false; // Parsing failed
        }
        // Check for leftover characters
        char c;
        if (iss >> c) {
            return false; // There are additional characters after the number
        }
        return true; // Successfully parsed
    }

    int main() {
        std::string input = "1234";
        int value;
        if (safe_stoi(input, value)) {
            std::cout << "Parsed integer: " << value << std::endl;
        } else {
            std::cout << "Failed to parse integer." << std::endl;
        }
        return 0;
    }
    

This function attempts to parse the string using an `istringstream`. If parsing fails or if there are leftover characters after the number, it returns `false`. Otherwise, it stores the parsed integer in the provided reference and returns `true`.

Conclusion

Using `std::istringstream` to parse strings into integers is a robust alternative to `stoi` or `stol`, as it avoids exceptions and provides more control over the parsing process. This method ensures that your program can handle invalid input gracefully, improving its overall reliability.