// GuessAWord.cpp (c) Kari Laitinen // http://www.naturalprogramming.com // 2013-11-14 File created. // 2013-11-14 Last modification. /* This program is a simple computer game in which the player has to guess the characters of a word, or the player may also try to guess the whole word. This program demonstrates, among other things, various string operations. */ #include #include using namespace std ; int main() { cout << "\n This is a GUESS-A-WORD game. \n" ; string word_to_be_guessed = "VIENNA" ; string guessed_characters( word_to_be_guessed.length(), '_' ) ; // Now guessed_characters refers to a string that has as many // underscore characters as the word to be guessed. bool game_is_over = false ; while ( game_is_over == false ) { cout << " " + guessed_characters + " " + "Give a character or word: " ; string player_input ; getline( cin, player_input ) ; // The following loop uses to bit operator & to convert the // player input to uppercase letters. (Note that this program may // not work with non-English letters.) for ( int character_index = 0 ; character_index < player_input.length() ; character_index ++ ) { player_input[ character_index ] = player_input[ character_index ] & 0xDF ; } if ( player_input.length() == 1 ) { // The player gave a single character for ( int character_index = 0 ; character_index < word_to_be_guessed.length() ; character_index ++ ) { if ( word_to_be_guessed[ character_index ] == player_input[ 0 ] ) { guessed_characters[ character_index ] = player_input[ 0 ] ; } } if ( guessed_characters.find( '_' ) == string::npos ) { // "_" is not a substring in guessed characters. // This means that all characters have been guessed. game_is_over = true ; cout << " " << guessed_characters << " Congratulations! \n\n" ; } } else if ( player_input.length() > 1 ) { // The player tried to guess the whole word. if ( player_input == word_to_be_guessed ) { // The player made a correct guess. game_is_over = true ; cout << "\n Congratulations! \n\n" ; } } else { game_is_over = true ; cout << " \n Game over. \n\n" ; } } }