MR. Coleman teaches second grade at Hinesbrook. On days when the weather is bad
ID: 3534768 • Letter: M
Question
MR. Coleman teaches second grade at Hinesbrook. On days when the weather is bad and the students cannot go outside to play, he spends recess time playing a simplified version of the hangman game with his class. Thegame requires two people to play. Currently, Mr. Coleman think of a word that has five letters.He then draws five dashes on the chalkboard--one for each letter in the word. One student then is chosen to guess the word, letter by letter. When the student guesses a correct letter, Mr. Coleman reeplaces the appropriate dash or dashes with the letter. For example, if the original word is moose and the student guesses the letter o, Mr. Coleman changes the five dashes on the chalkboard to -oo-. The game is over when the student either guessess all of the letters in the word or makes 10 incorrect guessess, whichever occurs first. Mr. Coleman wants a program that allows two students to play the game on the computer.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare variables
string origWord = "";
string letter = "";
char dashReplaced = 'N';
char gameOver = 'N';
int numIncorrect = 0;
string displayWord = "-----";
//get original word
do //begin loop
{
cout << "Enter a 5-letter word in uppercase: ";
getline(cin, origWord);
} while (origWord. length() != 5);
//clear the screen
system ("cls");
//start guessing
cout << "Guess this word: " <<
displayWord << endl;
while (gameOver == 'N')
{
cout << "Enter an uppercase letter: ";
cin >> letter;
//search for the letter in the original word
for (int x = 0; x < 5; x += 1)
{
//if the current character matches
//the letter, replace and corresponding
//dash in the displayWord variable and then
//set the dashReplaced variable to 'Y'
if (origWord.substr(x, 1) == letter)
{
displayWord.replace(x, 1, letter);
dashReplaced = 'Y';
} //end if
} //end for
//if a dash was replaced, check whether the
//displayWord variable contains any dashes
if (dashReplaced == 'Y')
{
//if the displayWord variable does not
//contain any dashes, the game is over
if (displayWord.find("-", 0) == -1)
{
gameOver = 'Y';
cout << endl << "Yes, the word is "
<< origWord << endl;
cout << "Great guessing!" << endl;
}
else //otherwise, continue guessing
{
cout << endl << "Guess this word: "
<< displayWord << endl;
dashReplaced = 'N';
} //end if
}
else //processed when dashReplaced contains 'N'
{
//add 1 to the number of incorrect guesses
numIncorrect += 1;
//if the number of incorrect guesses is 10,
//the game is over
if (numIncorrect == 10)
{
gameOver = 'Y';
cout << endl << "Sorry, the word is "
<< origWord << endl;
} //end if
//end if
} //end while
system ("pause");
return 0;
} //end of main function
}
Explanation / Answer
Please rate with 5 stars :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.