Skip to content

Instantly share code, notes, and snippets.

@Goom11
Forked from anonymous/hangman
Created January 4, 2013 23:41
Show Gist options
  • Save Goom11/4458529 to your computer and use it in GitHub Desktop.
Save Goom11/4458529 to your computer and use it in GitHub Desktop.
#include<iostream>
#include<cstring>
using namespace std;
const int MAX_WORD_LEN = 100;
const int TOTAL_LIVES = 10;
int find_len( const char word[] );
void clear_screen();
void create_hidden( const char word[] ,char hidden[] , int len );
int main(){
cout << "Welcome to Hangman\n" <<
"Please enter your word and then press enter: ";
char word[MAX_WORD_LEN + 1] = {'\0'};
cin.getline( word , 100 );
int len = find_len(word);
int lives = TOTAL_LIVES;
cout << len << endl;
char hidden[MAX_WORD_LEN + 1];
create_hidden( word , hidden , len );
cout << hidden;
char used[ MAX_WORD_LEN ] = {'\0'};
while( lives > 0 and strncmp( word , hidden , len ) != 0 ){
clear_screen();
cout << hidden << endl <<
"You have guessed the following: " <<
used << endl <<
"Please enter your guess: ";
char guess;
cin >> guess;
bool changed = false;
for(int i = 0 ; i < len ; i++ ){
if( guess == word[i]){
hidden[i] = guess;
changed = true;
}
}
if( changed == false ){
used[TOTAL_LIVES - lives] = guess;
lives--;
}
}
if( lives == 0 ){
cout << endl << endl << "Sorry, you lost, the word was: " <<
word << endl;
}
else
cout << endl << endl << "Congratulations on guessing: " <<
word << endl;
}
int find_len( const char word[] ){
int i = 0;
while( word[i] != '\0' )
i++;
return i;
}
void clear_screen(){
for( int i = 0 ; i < 100 ; i++ ){
cout << endl;
}
}
void create_hidden( const char word[] , char hidden[] , int len ){
for(int i = 0 ; i < len ; i++ ){
if( isspace( word[i]))
hidden[i] = ' ';
else
hidden[i] = '-';
}
hidden[len] = '\0';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment