angelreyes17
angelreyes17

Reputation: 81

std::string::substr throws std::out_of_range but the arguments are in limit

I have a vector of strings:

vector<string> tokenTotals;

When push_back is called, a string of length 41 is stored and I must operate on each element of my vector and get two substrings, the first in range 0 to 28 and the second in range 29 to 36:

for(int i = 0; i < tokenTotals.size(); i++)
{
    size_t pos = tokenTotals[i].find(": ");
    cout << tokenTotals[i] << endl; // Show all strings - OK
    cout << tokenTotals[i].length() << endl; // Lenght: 41
    string first  = tokenTotals[i].substr(0, 28); // OK
    string second = tokenTotals[i].substr(29, 36); // ERROR
    cout << first << " * " << second << endl;
}

But when I try to get the second substring, I get the following error:

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

Any idea of what could have happened?

Upvotes: 2

Views: 1790

Answers (2)

LogicStuff
LogicStuff

Reputation: 19607

See the std::string::substr reference. The second parameter is the length of the substring, not the position of the character after the substring, so the result is an attempt to access elements out of range -std::out_of_range is thrown.

With tokenTotals[i].substr(0, 28) this mistake doesn't manifest, since the substring has both size and the position one past end 28.

Upvotes: 11

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22254

substr(29,36);

will attempt to get a string that starts at position 29 and has a size of 36 characters. Unfortunately 29 + 36 > 41

documentation

Upvotes: 7

Related Questions