Coders Packet

Simple Hangman Project with c++

By Madagoni Nikhitha

This is a simple game in which th user needs to guess letters to find the country name from the given list of countries within the given no. of chances for the user.

Basic Setup -

Each letter is represented by a star.
You have to type only one letter in one try
You have "n " tries to try and guess the word. (let say n=5)

***** (this represent a country name with 5 letters)

Guess a letter : (let say we guess 'I')

You found a letter! Isn't that exciting!
You have 5 guesses left.

I**** (more 4 letters to guess)

Guess a letter : (let say we guess 'g')

Whoops! That letter isn't in there!
You have 4 guesses left

I**** (more 4 letters to guess)

Guess a letter :
(this will continue until all the lives are finished or the user has guessed the country name)



We need to create an array of strings(country names) from which a random string is selected using the rand() function  for the player to guess and keep it in a variable  say s1.player have 5 chances of retrying another letter(n=5)          


Then, we need to convert all the letters in s1 to stars(*) and let it be s2.


1)Do the below process until no. of chances are left.

->ask the player to guess a letter and take the input,k.

->Let us create another string s3=s2;

->[*if (k) is present in s1,

  We need to update the letter in place of the star(*) using for loop. 

   i.e; s2 is updated if k is present in s1.

   If s2 is not updated i.e; updated s2 same as s3;

   We should say the player that the letter is not present

   And no. of chance need to be decreased by 1;   i.e;n-1

  If s2 is updated i.e; updated s2 not equal to s3, we need to show the updated s2 and tell the player that he is correct.


ask the player to try again ]

->If updated s2=s1 then we need to break the while loop and the player wins



using namespace std;
int main() {
cout<<"welcome to hangman!guess a country name"<<endl<<"each letter is represented by *."<<endl<<"you have to type only one letter in one try and you have 5 chances to try and guess the word "<<endl;
srand (time(NULL));
string words[]={"india","phillippines","pakistan","nepal","malaysia"};
int randomindex=rand()%5;
string s1=words[randomindex];
string s2(s1.length(),'*');
int n=5;
char k;
cout<<"guess the letter:"<<endl;
string s3=s2;
for(int i=0;i<s1.length();i++){
cout<<"oops!that letter isn't there!"<<endl;
cout<<"you have "<<n<<" chances!"<<endl;
cout<<"you were hanged!!"<<endl;
cout<<"try again!"<<endl;}
cout<<"yeah you guessed right!!"<<endl;
cout<<"Yeah!!you got the word,congrats!"<<endl;
return 0;


Download Complete Code


No comments yet