Search code examples
c++stringloopserase

member function erase() not working in a loop


I'm programming a little game; but stringname.erase() seems to be not working in a 'for-loop' , I want to understand why, I have other alternatives, but I don't understand what's going on in the following code.

More explications of my situation (Important!):

guess is a char. 'tmgword' and 'word' are of type string, and: tmgword = word ;

what I understand from my code:

in the first time,the 'while'-loop verifies if there is 'guess' in the string 'tmpgword'. That is true and the for-loop is working fine, the right character(guess) that verifies the if-condition is erased.

in the second time: the 'while'-loop verifies again if there is 'guess' in the string 'tmpgword'. that is true, and hence we go into the 'for-loop' again; and then into the 'if'-block ( the right char is found ) but here erase() don't work, and we enter in an infinite loop.

when the program finds the right index using 'for-loop', I break, and I start the search from the beginning in case there are more occurrences of guess.

the problem is: the program finds 'guess' again but erase() won't delete it!

can someone explain please. Here is my code:

while (tmpgword.find(guess,0) != string::npos )
        {
            for (i = 0; i < word.size(); i++) // verify the input; 
            {

                if (word[i] == guess)
                {
                    encword[i] = word[i];//I don't think this line is important
                    tmpgword.erase(tmpgword.begin() + i);
                    break;
                }

            }
        }

Solution

  • After you do the first erase, the character positions in tmpgword are not the same as in word.

    string::find() returns the position of the element when it's found, so you can use that instead of looping through word.

    size_t pos = 0;
    while ((pos = tmpgword.find(guess, pos)) != string::npos) {
        tmpgword.erase(pos, 1);
    }
    

    I've used pos as the starting position for each call to find() so it starts from where it just erased, rather than searching from the beginning each time through (there can't be any occurrences before that, because they've all been erased).