Hangman game with strange bug.
I can't seem to track down where the issue with this program is. I've only just started coding C++ any help would be great.
I started off with two global char variables as I intended to use functions and wanted not to have to worry about inheritance or writing local variables. Problem was when I finished the code I realised functions weren't needed and moved the variables within int main(). Now the variables are full of ASCII characters.
Here's the code that works:
// Hangman game using 9 preset words
#include<iostream>
#include<cstring>
usingnamespace std;
char word[40];
char guess[40];
int main(){
char game;
int n;
char L;
int lives = 7;
//Menu system
for(;do{
cout <<
"The C++ Hangman Game. \n";cout <<
"Choose a game number (1-9, q to quit)";cin >> game;
}
while( game <'1' || game >'9' && game !='q');if (game =='q')return 0;
//Setting the word for the hangman game:
switch(game){
case'1':
strcpy(word,"namespace");
break;
case'2':
strcpy(word,"switch");
break;
case'3':
strcpy(word,"array");
break;
case'4':
strcpy(word,"function");
break;
case'5':
strcpy(word,"recursion");
break;
case'6':
strcpy(word,"pointer");
break;
case'7':
strcpy(word,"string");
break;
case'8':
strcpy(word,"c++");
break;
case'9':
strcpy(word,"double");
break;
}
//once choice is made exit menu
break;}
n = strlen(word);
for(n; n != 0; n--) strcat(guess,"_");/* Now there are 2 strings that contain the word to guess and the current guess (all _s). */
// game start proper
for(;
{
cout <<"Here's the word: " << guess;
cout <<"\nLives = " << lives;
cout <<"\nEnter a letter to guess: ";
cin >> L;
char *w;
char *g;
int right_wrong = 0;
w = word;
g = guess;
//check guess letter against word and copy over if right. Lose a life if wrong
while(*w){
if(*w == L){
*g = L;
right_wrong = 1;}
w++;
g++;
}
if(right_wrong)
cout <<"You're right\n";
elseif(!right_wrong){
cout <<"You're wrong\n";
lives--;}
// Win-lose condition check and exit
if(lives <= 0){
cout <<"\nYou lose!\n";
cout <<"Out of lives. The word was "<< word <<"\n";
break;}
if(!strcmp(word, guess)){
cout <<"You win!\n" <<"Word was " << word <<"\n";
break;}
}
return 0;
}

