string::iterator and erase problem

I am making my hangman clone and is stuck again in this function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int
word_handle::removeLetter( const char c )
{
    int flag = 0;
    for ( std::string::iterator it = wordToGuess_.begin();
        it != wordToGuess_.end();
        ++it )
    {
        if ( *it == c )
        {
            wordToGuess_.erase( it );
            flag = 1; // there is a c in the string
        }
    }
    return flag;
}

The problem is, for example, wordToGuess_ was "kangaroo", and the parameter was 'o', only one of 'o' in "kangaroo" is deleted, and if ever i remove one of 'o', in kangaroo, -> "kangaro", the program crashes ( BEX ) ?

Please help me.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <algorithm>

std::string remove_letter_easy( std::string str, char c )
{
    str.erase( std::remove( str.begin(), str.end(), c ), str.end() ) ;
    return str ;
}

std::string remove_letter( std::string str, char c )
{
    for( auto iter = str.begin() ; iter != str.end() ; )
    {
        if( *iter == c ) iter = str.erase(iter) ;
        else ++iter ;
    }
    return str ;
}

int main()
{
    const std::string txt = "abcdefghabcdefghabcd" ;
    std::cout << txt << '\n' ;
    std::cout << remove_letter_easy( txt, 'b' ) << '\n' ;
    std::cout << remove_letter( txt, 'e' ) << '\n' ;
}

http://coliru.stacked-crooked.com/a/a6032323c58bfcb3
Topic archived. No new replies allowed.