Hangman game must be in c++ Enter the max number of tries: 10 Guess a letter (yo
ID: 3858396 • Letter: H
Question
Hangman game must be in c++
Enter the max number of tries: 10 Guess a letter (you have 10 tries left): a Right! Word so far a***a Guess a letter (you have 9 tries left): x Wrong! Try again. Word so far is: a***a Guess a letter (you have 8 tries left): 1 Right! Word so far: a1* Guess a letter (you have 7 tries left): a a' has already been used. Try again. Guess a letter (you have 7 tries left): u Wrong! Try again. Word so far is: al**a Guess a letter (you have 6 tries left): p Right Word so far: alp*a Guess a letter (you have 5 tries left): h You win! Another run: Enter the max number of tries: 4 Guess a letter (you have 4 tries left): o Right! Word so far: *o* Guess a letter (you have 3 tries left): a Wrong! Try again. Word so far is: *o* Guess a letter (you have 2 tries left): b Wrong! Try again. Word so far is: *o* Guess a letter (you have 1 try left) x You loose! The word is: dogExplanation / Answer
#include <iostream>
#include <string>
using namespace std;
int main()
{
int tttt;
cout<<"Enter max number of tries ";
cin>>tttt;
cout << "Enter the word for other player to guess" << endl;
string word;
cin>>word;
string copy = word;
string Underscore;
for(int i=0; i!=word.length(); i++){
if(word.at(i) == ' '){
Underscore += " ";
} else{
Underscore += "*";
}
}
string guess;
int wrong=0;
while(1){
if(wrong == tttt){
cout << "You Lose! The word was: " << word << endl;
break;
}
cout << Underscore << endl;
if(Underscore == word){
cout << "You win!" << endl;
break;
}
cout << "Guess a letter (You have " << tttt - wrong << " tries left)"<< endl;
cin>>guess;
if(guess.length() > 1){
if(guess == word){
cout << "That's right, you win!" << endl;
break;
} else{
cout << "wrong word " << endl;
wrong++;
}
} else if(copy.find(guess) != -1){
cout<<"right word so far"<<endl;
while(copy.find(guess) != -1){
Underscore.replace(copy.find(guess), 1, guess);
copy.replace(copy.find(guess), 1, "_");
}
} else{
cout << "wrong,try again" << endl;
wrong++;
}
cout << endl;
}
return 0;
}
==========================
Enter max number of tries 10
Enter the word for other player to guess
akshay ******
Guess a letter (You have 10 tries left)
a
right word so far a***a*
Guess a letter (You have 10 tries left)
k
right word so far ak**a*
Guess a letter (You have 10 tries left) h
right word so far ak*ha*
Guess a letter (You have 10 tries left)
y
right word so far ak*hay
Guess a letter (You have 10 tries left)
s
right word so far akshay
You win!
==================================
I am accepting string from user or else you can hardcode if you want
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.