Ok so I completed my hangman code but now I have to read the words from a .txt. I have looked at numerous codes and examples but cant get it to work at all. Any help I would be grateful.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
using namespace std;
string GuessWord;
int missed;
string HiddenWord;
string used;
bool match(char letter, string word);
char askGuess(string usedLettersStr);
bool PlayAgain();
int main()
{
srand(time(0));
// I had a real hard time getting all the features of the game to work correctly together. After hours of fixing one thing while messing up another ,
// I asked my nephew to take a look at it. He suggested using the "vector<string>words" instead of "string words[]" to help keep track of the size of the word.
// I didn't think it would be a problem since vectors are covered in the book and you said we could use things not directly taught through the book.
vector<string> words;
words.push_back("resistor");
words.push_back("inductor");
words.push_back("capacitor");
words.push_back("diode");
words.push_back("transistor");
words.push_back("circuit");
bool done = false;
do
{
//Radomize words
random_shuffle(words.begin(), words.end());
//Word to guess
GuessWord = words[0];
//Hide word
HiddenWord = string(GuessWord.size(), '*');
used = "";
while (HiddenWord != GuessWord)
{
used += askGuess(used);
}
} while (PlayAgain());
return 0;
}
//
inline bool match(char letter, string word)
{
return (word.find(letter) != string::npos);
}
//Keep track of guesses
char askGuess(string usedLettersStr)
{
char guess;
cout << "(Guess) Enter a letter in word " << HiddenWord << " > ";
cin >> guess;
guess = tolower(guess);
//Repeated guess
while (match(guess, used))
{
cout << " " << guess << " is already in the word" << endl;
cout << "(Guess) Enter a letter in word " << HiddenWord << " > " << endl;
cin >> guess;
guess = tolower(guess);
}
//Good Guess (replace asterisks with letter)
if (match(guess, GuessWord))
{
cout << "(Guess) Enter a letter in word " << HiddenWord << " > " << endl;
for (int i = 0; i < GuessWord.length(); ++i)
if (GuessWord[i] == guess)
HiddenWord[i] = guess;
}
//Bad Guess
if (!match(guess, GuessWord))
{
cout << " " << guess << " is not in the word." << endl;
++missed;
}
return guess;
}
//End game and aske to play again
bool PlayAgain()
{
char again;
cout << "The word is " << GuessWord << ". You missed " << missed << " time(s)" << endl;
cout << "\n\nDo you want to guess for another word? Enter y or n ";
cin >> again;
cin.clear(); //clear and ignore cin
cin.ignore();
again = tolower(again);
system("cls");
return (again == 'y');
}