Simple Hangman Project with c++

Description -

The User needs to input letters to find the country name , user will be given 'n' number of chances and the user needs to guess the respective letters

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 finish or the user has guessed the country name)

Algorithm:

Step1:

We need to create an array of strings(country names) from which a random string is selected using 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)          

Step2:

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

Step3:

while(no.of chances>0){

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 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 chances need to be decreased by 1;   i.e;n-1

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

*Else:

ask the player to try again ]

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

}

code:

#include <iostream>

#include<stdlib.h>

#include<time.h>

#include<string>

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","philippines","pakistan","nepal","malaysia"};

int randomindex=rand()%5;

string s1=words[randomindex];

string s2(s1.length(),'*');

cout<<s2<<endl;

int n=5;

while(n>0){

char k;

cout<<"guess the letter:"<<endl;

cin>>k;

string s3=s2;

for(int i=0;i<s1.length();i++){

if(s1[i]==k){

s2[i]=k;

}

}

if(s2==s3){

cout<<"oops!that letter isn't there!"<<endl;

n--;

cout<<"you have "<<n<<" chances!"<<endl;

if(n==0){

cout<<"you were hanged!!"<<endl;

}

else{

cout<<"try again!"<<endl;}

}

else{

cout<<s2<<endl;

cout<<"hey..you guessed right!!"<<endl;

 

}

if(s1==s2){

cout<<"Yeah!!you got the word,congrats!"<<endl;

break;

}

}

return 0;

}

Hope you understand the project.Happy Learning!!