Reputation: 469
I'm creating a hangman game for school. The words to be guessed are pulled from a data file, the program selects the last word from the file as the word to be used for the game, 'words' is the variable I used for this, as the game goes, the user guesses a letter and if the letter is in the word it is correct and if not it is incorrect and the program displays a "board" or picture of the hangman progressively.
I used str.find()
to see if the letter guessed is in the word, the code is as follows:
while (wrongGuess < 7){
cout << "\nGuess a letter in the word: " << endl;
cin >> guess;
if (words.find(guess)==true){
cout << "Correct! " << guess << " is FOUND in the word " << word << endl;
continue;}
else
{cout << guess << " is NOT FOUND in the word " << endl;
wrongGuess++;
if(wrongGuess == 1)
cout << board2;
else if(wrongGuess == 2)
cout << board3;
else if(wrongGuess == 3)
cout << board4;
else if(wrongGuess == 4)
cout << board5;
else if(wrongGuess == 5)
cout << board6;
else if(wrongGuess == 6)
cout << board7 << "\nSorry Game Over";
}
The word that is used is programming
.
My problem is sometimes when I enter a correct letter (like r
) it tells me I'm right, other times I enter a different correct letter (p
) and the program tells me I am wrong.
What do I have wrong?
Upvotes: 0
Views: 873
Reputation: 47794
Use std::string::npos
to check th find
result.
if( words.find(guess) != std::string::npos)
{
//...
}
else
{
}
Upvotes: 1
Reputation: 4715
std::basic_string::find
aka. std::string::find
returns the position of the given character in the string, not a bool
.
The code you've posted sometimes works because true
decays to 1
and if the searched character is on position 1, the condition is true.
To fix it, you should do this:
...
if (words.find(guess)!=std::string::npos){
...
Upvotes: 1