2

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?

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
angelreyes17
  • 81
  • 1
  • 1
  • 5

2 Answers2

11

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.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
7
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

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82