-1

So I have simple JSON string that I'm iterating through with a for loop (don't ask why I'm not using a json parser). In this loop I want to kick out {, } and '' (the misplaced } is just there for debugging reasons) Here is the code:

std::string str("{'pi': 3.141, 'happy': }true }");
for (int i = 0; i < str.length(); i++)
{
    char temp = str[i];
    if (temp == '{' || temp == '}' || temp == ' ' )
        str.erase(i, 1);
}

Not very complicated and it basically works just fine but for some reason the } gets skipped. It just iterates through the string like it wouldn't even be there. Can anyone reproduce this behavior? I'm totally out of ideas what could be wrong here.

EDIT: Ok, I can see how this might be a duplicate of the other post but to be fair it's hard to stumble upon a post about vectors when having problems with a string

alektron
  • 87
  • 1
  • 10
  • You can only use a for loop if the number of characters in the string stays the same. But you are removing characters while iterating over the string. – Aedvald Tseh Jun 12 '17 at 16:08
  • when some charecter is removed from string, the size of string is changed, and the index positioning not just next element of current( removed) element, but next to that – zapredelom Jun 12 '17 at 16:08

1 Answers1

0

It iterates through the string as if the brace weren't even there, because each closing brace is preceded by a space. Take a simpler example:

abc }def

The loop reaches i=3, the space, deletes it, then proceeds to i=4, which is now the 'd'.

You can fix this by decrementing i when you erase a character.

Beta
  • 96,650
  • 16
  • 149
  • 150
  • Oh my... I actually thought about the fact that making the string shorter in the process might cause problems but as it worked for all the other characters I assumed it works fine. Of course I had to put my testing symbol after a space as well... – alektron Jun 12 '17 at 16:12