Here's my code for a Hangman game I'm developing:
#include <iostream>
using namespace std;
const char *const Words[]={"America", "Barrack", "country", "doctors","salamat"};
#define NWORDS (sizeof Words/sizeof (char *))
int main()
{
const char *toguess=Words[0];
char guess[15] = " ";
int numguesses = 1;
char ch;
string str1;
string str2; //
string mychars("");
unsigned wordno=1;
std::cout << "Welcome to Hangman!\nRaymund is to be executed for a crime he committed.\nTo save him, you need to guess any of the five words provided by the judge.\nYou are given only 15 tries to solve any of the 5 words.\nGoodluck!\n\nNow enter a number to select the word to guess[1.." << NWORDS << "]: ";
cin >> wordno;
toguess = Words[wordno-1];
bool playing = true;
while (playing)
{
cout << "Enter your guess:" ;
cin >> ch;
if (0>ch>5)
{
cout << "Choose only a number from 1 to 5!" << endl;
}
else (1<=ch=<5)
{
mychars = mychars + ch;
cout << "Your wrong guesses so far: " << mychars << endl;
cout << endl;
const char *tp ;
char *gp;
for (tp=toguess, gp=guess;*tp; tp++, gp++) {
if(ch == *tp)
*gp=ch;
}
str1 = toguess;
str2 = guess;
for(gp=guess; *gp; gp++)
cout << *gp << " ";
cout << endl;
for(int i=1; i <= str1.length();i++)
cout << "- ";
cout << endl;
if ( str1==str2)
{
cout << "Conrats! You got it right!" << endl ;
playing= false;
}
else
{
numguesses = numguesses + 1;
if (numguesses>15)
{
cout<<endl<<endl
<<" +----+ "<<endl
<<" | | "<<endl
<<" | O "<<endl
<<" | /|\\ "<<endl
<<" | / \\ "<<endl
<<" |You ran out of guesses! "<<endl
<<" ============"<<endl<<endl;
playing=false;
}
} // else
} // else
} // loop
cout << " Thanks for playing! " << endl;
return 0;
}
I want to add something in this part
mychars = mychars + ch;
cout << "Your wrong guesses so far: " << mychars << endl;
cout << endl;
such that I can count the number of tries left by the player. My plan is to count the letters in mychars then store that number in a variable and subtract the variable from 15. I wonder if that's right? Also, is my code generally OK? Thanks for the help!