jeudi 11 février 2021

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

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.

Aucun commentaire:

Enregistrer un commentaire