< Previous | Contents | Next >

Getting the Player’s Guess

Next I get the players guess.

char guess;

cout << "\n\nEnter your guess: "; cin >> guess;

guess = toupper(guess); //make uppercase since secret word in uppercase while (used.find(guess) != string::npos)

{

cout << "\nYou’ve already guessed " << guess << endl; cout << "Enter your guess: ";

cin >> guess;

guess = toupper(guess);

}


used += guess;


if (THE_WORD.find(guess) != string::npos)

{

cout << "That’s right! " << guess << " is in the word.\n";


//update soFar to include newly guessed letter for (int i = 0; i < THE_WORD.length(); ++i)

{

if (THE_WORD[i] == guess)

{

soFar[i] = guess;

}

}

}

else

{

cout << "Sorry, " << guess << " isn’t in the word.\n";

++wrong;

}

}

Summary 145


I convert the guess to uppercase using the function uppercase(), which is defined in the file cctype. I do this so I can compare uppercase letters to uppercase letters when Im checking a guess against the letters of the secret word.

If the player guesses a letter that he or she has already guessed, I make the player guess again. If the player guesses a letter correctly, I update the word guessed so far. Otherwise, I tell the player the guess is not in the secret word and I increase the number of incorrect guesses the player has made.