Why is my if statement not evaluating false when it should be?

Viewed 79

In this part of my program, I want to take out the leading 0s in the string highScore. Here is what I have (not the entire program; this is just the part I'm having issues with):

//take out leading 0s
for (int i = 0; highScore.at(i) != '\0'; i++)
{
    if (highScore.at(i) == '0')
        highScore = highScore.erase(0, 1);
    else
      break;
}

The highScore string contains the string "000500000" in it, so after the variable i becomes 3, it should leave the loop (at least, that's what I want it to do) but instead it continues to loop through the string 2 more times and then outputs this error:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 5) >= this->size() (which is 4)

I am a little confused about this since I don't think I'm doing anything that would throw the string out of range.

2 Answers

You're both shortening the string and advancing the subscript. That takes you out of bounds pretty quickly. Your if should always test .at(0), and your loop, as others noted above, should test the size(). You can't look for the end with '\0'.

The problem is every time you call highScore.erase(), the length of String highScore gets changed. I prefer you to count the number of zeroes first, and then apply .erase() at the end. Have a look

int zeroCount = 0;
for(int i=0; i<highScore.length(); i++){
     if(highScore.at(i) == '0'){
          zeroCount++;
     }
     else{
          break;
     }
}
highScore.erase(0,c);
Related