Terminate called after throwing an instance of ‘std::invalid_argument’ what(): stoi

terminate called after throwing an instance of ‘std::invalid_argument’ what(): stoi

The error message you are encountering is related to the std::invalid_argument exception being thrown when using the stoi function.

The stoi function in C++ is used to convert a string to an integer. It throws an std::invalid_argument exception if the string passed as an argument cannot be converted to an integer.

Here’s an example that shows how stoi can throw an std::invalid_argument exception:

int main() {
    std::string str = "abc";
    int num = std::stoi(str);
    return 0;
}

In this example, we are attempting to convert the string “abc” to an integer using stoi. Since “abc” is not a valid representation of an integer, the std::invalid_argument exception is thrown.

To prevent the exception from being thrown, you can add error handling code. One way to do this is by using a try-catch block to catch the std::invalid_argument exception:

int main() {
    std::string str = "abc";
    try {
        int num = std::stoi(str);
    } catch (const std::invalid_argument& e) {
        // Handle the exception here
        std::cout << "Invalid argument: " << e.what() << std::endl;
    }
    return 0;
}

In this modified example, the std::invalid_argument exception is caught in the catch block, and appropriate error handling code can be added. In this case, we simply print the exception message using e.what().

Similar post

Leave a comment