I am having an issue with the for
loop near the end of this code.
The loop is for a hangman game, and essentially the loop cycles through the char
array with the secret word, and compares the user guess to each element in the char
array. If it is found, it updates the output to show the letter and resets the counter to 0, or else if the counter equals the length of the secret word, that means the loop did not find the char
and it should both add one to the display (for the hangman gallows) and place the incorrect guess in the wrong guess array.
The problem I am having here is that, for the most part the loop works as intended, but occasionally it will read a correct answer as being both correct and still places it within the wrong guess array, as well as increment the gallows display value.
It does this seemingly at random, and only when I play a second game. I thought it was an issue with the counter, but I have that reset to 0 both at the start of the while
loop and reset to zero in the for
loop if the correct answer is found.
So I don't know why it would read a correct answer as correct and still place it in the wrongChoice
array, since the counter at that point should not be wordLength - 1
. Here is the code:
while(!winner)
{
count = 0;
for(int i = 0; i < secretWord.length(); i++)
cout << userPrompt[i] << " ";
cout << "\n" << endl;
cout << "Wrong Guess: ";
for(int i = 0; i < (secretWord.length() + 6); i++)
{
cout << userChoice[i] << " ";
}
cout << "\n" << endl;
displayGallows(display);
if(display == 6)
{
cout << "Sorry, you lost!" << endl;
break;
}
cout << "Enter a letter: ";
cin >> userGuess;
while(!cin)
{
cin.ignore();
cin.clear();
cin.sync();
cout << "Error reading input character! Try Again!" << endl;
cout << "Enter a letter: ";
cin >> userGuess;
}
guessCount++;
cin.ignore();
for(int i = 0; i < secretWord.length(); i++)
{
if(word[i] == tolower(userGuess))
{
userPrompt[i] = tolower(userGuess);
count = 0;
}
else if(count == (wordLength - 1))
{
display++;
userChoice[guessCount - 1] = toupper(userGuess);
}
count++;
}
winner = checkWin(word, userPrompt, display, secretWord);
}
again = playAgain();