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

terminate called after throwing an instance of ‘std::out_of_range’

This error message usually occurs when you are trying to access an element of a container (such as an array, vector, or string) using an index that is out of range or exceeds the container’s size.

In the specific case of “stoi”, it refers to the function for converting a string to an integer in C++. The “stoi” function throws an “std::out_of_range” exception if the string cannot be converted to a valid integer.

Here’s an example to illustrate this error:

        
#include <iostream>
#include <string>

int main() {
    std::string str = "abc"; // Invalid integer string
    int num = std::stoi(str); // stoi throws std::out_of_range exception
    std::cout << num << std::endl; // This line won't be executed
    return 0; // Program terminates after the exception is thrown
}
        
    

In the above example, the string "abc" cannot be converted to a valid integer, so the "stoi" function throws an "std::out_of_range" exception. As a result, the program terminates without reaching the line that prints the value of "num".

To avoid this error, you should ensure that the string you are trying to convert is a valid integer representation. You can use error handling techniques such as try-catch blocks to catch the exception and handle it appropriately.

Similar post

Leave a comment