Out of Range Error with for statement

119 views Asked by At

I'm trying to trim the whitespace from the front of my string (classes). For some reason everytime I run the code I get an error message kicked back and I have no idea how to fix it.

void format_classes(string& classes)
{

  int n = classes.length();

  for (int i=0; i<n; i++)
  {
    if(classes[i] != ' ')
    {
        classes.erase(classes[0], classes[i]);
        break;
    }
  }     
}

The code above will receive something like " PhySiCS 101 lAB" and I have to return it without the whitespace out front.

the error message I have been receiving is:

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::erase

I'm still very new to coding so maybe a hint in the right direction instead of the answer so I can learn from my mistakes.

3

There are 3 answers

1
Paul Roub On BEST ANSWER

erase() takes a starting position and a length. That is, numbers. You're passing the characters at those points. So if the string is:

"  foo"

you're basically saying:

classes.erase(' ', 'f');

or

classes.erase(32, 102);

which are certainly out of the range of your 5-character string.

Try:

classes.erase(0, i);
0
Rook On

I'm a little late on this one, but you can do this without doing the iteration yourself, simply by doing something like this:

classes.erase(0, classes.find_first_not_of(' '));

This will work fine on empty strings and strings with leading whitespace, so no additional checking is required. It is generally good practise to use standard library features, especially when they make your code a bit shorter and perhaps even more readable.

I'm not certain, but I think the other methods used here (repeatedly erasing the first character) cause the underlying string buffer to be repeatedly copied and/or reallocated so this way might be a bit more efficient.

Also, it might be worth considering that there's more than one kind of whitespace, such as tabs. find_first_not_of can do stuff like this as well:

classes.erase(0, classes.find_first_not_of(" \t"));

There's also unicode, but that's a whole other can of worms for another time.

3
St0fF On

Your solution should look more like:

int i(0);
while((i < classes.length()) && (classes[i] == ' ')) ++i;
classes.erase(0,i);

@Paul Roub has explained it very well, already.