I am making a hangman program for school that uses a function for the player to input their guess and a seperate function to test whether or not their guessed letter is in the word. The program worked fine without the function to test the players guess but when i copied the code from the main program and turned it into the function i had to change most of the variables to global. All but one is working, my "soFar" string is supposed to change the randomly choosen word to "-" and it uses the ".size" function to do so. When I ran the program it didn't want to work any more. Any advice would be greatly appreciated. Here's my code:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cctype>
#include <conio.h>
using namespace std;
char enterGuess(string ask);
void testGuess(char playerGuess);
char guess;
vector<string> words; //collection of possible words to guess
const string THE_WORD = words[0];
double wordSize = THE_WORD.size();
string soFar(wordSize, '-');
string used = "";
int wrong = 0;
int main()
{
//setup
const int MAX_WRONG = 8; //maximum number of incorrect guesses allowed
words.push_back("GUESS");
words.push_back("HANGMAN");
words.push_back("DIFFICULT");
srand(time(0));
random_shuffle(words.begin(), words.end());
cout << "Welcome to Hangman. Good luck!\n";
//main loop
while ((wrong < MAX_WRONG) && (soFar != THE_WORD))
{
cout << "\n\nYou have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";
cout << "\nYou've used the following letters:\n" << used << endl;
cout << "\nSo far, the word is:\n" << soFar << endl;
guess = enterGuess("\n\nEnter your guess: ");
guess = toupper(guess); //make uppercase since secret word is in uppercase
while (used.find(guess) != string::npos)
{
cout << "\nYou've already guessed " << guess << endl;
cout << "Enter your guess ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
testGuess(guess);
}
//shut down
if (wrong == MAX_WRONG)
cout << "\nYou've been hanged!";
else
cout << "\nYou guessed it!";
cout << "The word was " << THE_WORD << endl;
getch();
}
char enterGuess(string ask)
{
char playerGuess;
cout << ask;
cin >> playerGuess;
return playerGuess;
}
void testGuess(char playerGuess)
{
if (THE_WORD.find(guess) != string::npos)
{
cout << "That's right! " << guess << " is in the word.\n";
// update soFar to include the newly guessed letter
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;
}
}