Hey guys, my next task is to split up the main function into separate functions; it compiles but when I play the hangman game, it doesn't replace the dash with the appropriate lettering. Everything else seems to work.
// Hangman Game Program in main()
#include <iostream> // Input/Output stream
#include <string> // String functions
#include <ctime> // Data and Time information
#include <cctype> // Transform individual Characters/ Converting characters to uppercase
#include <vector> // Data/Element containers
#include <algorithm> // Collection of functions designed for ranges of elements
usingnamespace std;
char getGuess();
void isGuessInWord(string, char, string);
string used = "";
int wrong = 0;
int main(){
//setup
constint MAX_WRONG = 8; // Create a new integer constant that holds the amount of wrong tries the user makes.
vector<string> words; // Vector with string elements that has a collection of possible words to guess.
words.push_back("GUESS");
words.push_back("HANGMAN");
words.push_back("DIFFICULT");
srand(static_cast<unsignedint>(time(0))); // Random generator that uses the time as the seed.
random_shuffle(words.begin(), words.end()); // Shuffles the words from begin to end in a random sequence determined by the generator seed.
const string THE_WORD = words[0]; // Number of incorrect guesses
string soFar(THE_WORD.size(), '-'); // Word guessed so far
while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) {
cout << "\n\nYou have " << (MAX_WRONG - wrong);
cout << " incorrect guesses left.\n";
cout << "\nYou've used the following letters:\n" << used << endl;
cout << "\nSo far, the word is: \n" << soFar << endl;
char guess;
guess = getGuess();
while (used.find(guess) != string::npos) {
cout << "\nYou've already guessed " << guess << endl;
cout << "Enter your guess: ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
isGuessInWord(THE_WORD, guess, soFar);
}
if (wrong == MAX_WRONG) {
cout << "\nYou've been hanged!";
}
else {
cout << "\nYou guessed it!";
}
cout << "\nThe word was " << THE_WORD << endl;
return 0;
}
char getGuess() {
char guess;
cout << "\n\nEnter your guess: ";
cin >> guess;
guess = toupper(guess);
return guess;
}
void isGuessInWord(string THE_WORD, char guess, string soFar) {
if (THE_WORD.find(guess) != string::npos) {
cout << "\nThat's right!" << guess << " is in the word.\n";
for (int i = 0; i < THE_WORD.length(); ++i){
if (THE_WORD[i] == guess) {
soFar[i] = guess;
}
}
}
else {
cout << "Sorry, " << guess << " isn't in the word.\n";
++wrong;
}
}
isGuessInWord(), when called, receives copies of its parameters that it works on, so any changes you make to its parameters does not affect main() at all. You could pass soFar by reference in order to have the changes reflected outside of the function.