String replacing Hangman

Hangman code, I need to replace all asterisks where letter is present, not just the first one. Also when I guess the correct letter, it still adds one to my guesses for some reason, except for the first time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
while ( guesses < max_guesses )
        {
            cout << "Guess a letter: ";
            cin >> str2;                         //input letter guess
            for ( k = 0; k <= str1.length(); k++ )
            {
                if( str2 == str1[k] )             //is the input letter in our word
                {
                    asterisks.replace( k, 1, 1, str2 );   //replace asterisks with letter
                    cout << "Correct letter" << endl;
                    cout << asterisks << endl;
                    break;
                }
                else
                {
                    cout << "Wrong letter" << endl;
                    guesses = guesses + miss;     //wrong guess
                    cout << "Used guesses: " << guesses << endl;
                    cout << "Guesses left: " << max_guesses - guesses << endl;
                }
            }
        }


Str1 is the word we're guessing, str2 is the letter we've guessed.
Get rid of the break in your if statement.
for ( k = 0; k <= str1.length(); k++ )
Looks like a buffer overflow problem, remember arrays start at zero and stop at size - 1.

Str1 is the word we're guessing, str2 is the letter we've guessed.
str2 == str1[k]
IMO, this is confusion waiting to happen. Use meaningful names, perhaps something like word and guess.

Also when I guess the correct letter, it still adds one to my guesses for some reason, except for the first time.

If this is indeed the actual code I don't see where guesses will ever be changed unless the if() condition fails.
Topic archived. No new replies allowed.