#include "stdafx.h" #include <string> #include <iostream> #include <ctime> #include <cctype> #include <vector> #include <algorithm> using namespace std; char getGuess(string &used); //Prototype Function Declaration char EntryIsCorrect(); //Prototype Function Declaration int main() { // set-up const int MAX_Incorrect = 5; // maximum number of incorrect guesses allowed vector<string> words; // collection of possible words to guess words.push_back("CALIFORNIA"); srand(static_cast<unsigned int>(time(0))); random_shuffle(words.begin(), words.end()); const string SECRET_WORD = words[0]; // word to guess int wrong = 0; // number of incorrect guesses string soFar(SECRET_WORD.size(), '-'); // word guessed so far string used = ""; // letters already guessed cout << "Welcome to the game of Hangman!\n"; // main loop while ((wrong < MAX_Incorrect) && (soFar != SECRET_WORD)) { cout << "\n\nYou have " << (MAX_Incorrect - wrong); cout << " incorrect guesses left.\n"; cout << "\nYou have used the following letters:\n" << used << endl; cout << "\nCurrently, the word is:\n" << soFar << endl; char guess = getGuess(used); if (SECRET_WORD.find(guess) != string::npos) { cout << "That is correct! " << guess << " is in the word.\n"; // update soFar to include newly guessed letter for (unsigned int i = 0; i < SECRET_WORD.length(); ++i) { if (SECRET_WORD[i] == guess) { soFar[i] = guess; } } } else { cout << "Incorrect! " << guess << " is not in the word.\n"; ++wrong; } } // shut down if (wrong == MAX_Incorrect) cout << "\nYou have lost!"; else cout << "\nYou guessed the word!"; cout << "\nThe word was " << SECRET_WORD << endl; system("pause"); return 0; } //----getGuess Function Return starts here--- char getGuess(string & used) { char guess; cout << "\n\nEnter your guess: "; cin >> guess; guess = toupper(guess); //make uppercase since secret word in uppercase while (used.find(guess) != string::npos) //if guess IS in the string, ask for guess again in while loop { cout << "\nYou have already guessed " << guess << endl; cout << "Please enter another guess: "; cin >> guess; guess = toupper(guess); } used += guess; return guess; } |
|
|