成员函数 erase() 不在循环中工作

member function erase() not working in a loop

我正在编写一个小游戏;但是 stringname.erase() 似乎在 'for-loop' 中不起作用,我想了解为什么,我有其他选择,但我不明白下面的代码是怎么回事。

更多说明我的情况(重要!)

猜测是一个字符。 'tmgword' 和 'word' 是字符串类型,并且: tmgword = word ;

我从我的代码中了解到:

第一次,'while'循环验证字符串'tmpgword'中是否有'guess'。 这是真的,for 循环工作正常,验证 if 条件的正确字符(猜测)被擦除。

第二次:'while'循环再次验证字符串'tmpgword'中是否有'guess'。 这是真的,因此我们再次进入 'for-loop';然后进入 'if' 块(找到正确的字符)但这里 erase() 不起作用,我们进入无限循环。

当程序使用 'for-loop' 找到正确的索引时,我中断并从头开始搜索,以防出现更多的猜测。

问题是:程序再次找到 'guess' 但 erase() 不会删除它!

谁能解释一下。这是我的代码:

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;
                }

            }
        }

执行第一次擦除后,tmpgword 中的字符位置与 word 中的字符位置不同。

string::find() returns 找到元素时的位置,因此您可以使用它而不是遍历 word.

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

我使用 pos 作为每次调用 find() 的起始位置,所以它从刚刚删除的地方开始,而不是每次都从头开始搜索(不能是之前发生的任何事件,因为它们都已被删除)。