Search code examples
c++stringvoiderase

Out of Range Error with for statement


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.


Solution

  • 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);