terminate called after throwing an instance of ‘std::out_of_range’ what(): basic_string::substr

What you experience is probably a case of an exception falling off main(), which terminates the program and gives an OS-specific error message like the one you posted.

As a first measure, you can catch exceptions in main(). This will prevent your program from crashing.

#include <exception>
#include <iostream>

int main()
{
    try
    {
        // do stuff
    }
    catch (std::exception const &exc)
    {
        std::cerr << "Exception caught " << exc.what() << "\n";
    }
    catch (...)
    {
        std::cerr << "Unknown exception caught\n";
    }
}

Now that you have this mechanism in place, you can actually hunt down the error.

Looking at your code, it could be that n_cartelle has less than 4 elements, caused perhaps by n_cartelle.txt containing only 3 lines. This would mean that n_cartelle[0]n_cartelle[1] and n_cartelle[2] would be fine, but trying to access n_cartelle[3] and anything beyond would be undefined behaviour, which basically means that anything can happen. So first make sure that n_cartelle actually has 4 elements and that your program has defined behaviour.

The next thing which could go wrong (more likely, to be honest) is your substr() call. When you try to call substr() with “impossible” arguments, for example getting the substring starting at character 10 of a string containing only 5 characters, then the behaviour is a defined error – a std::out_of_range exception is thrown. The same happens (indirectly, almost every time) when you accidentally try to pass a negative number as the first argument of substr(). Due to the internal workings of a std::string, a negative number would be converted to a huge positive number, certainly much longer than the string, and result in the same std::out_of_range exception.

So, if one of your lines has a length less than 3 characters, size() - 3 is negative and what I just explained happens.

Leave a Comment