- Code: Select all
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
class hangman
{
public:
hangman(); // prompt names.
void readWords(); //read words from a txt file and store them into a vector.
void setWord();// sets a random word from the vector
void promptUser();
string getWord() { return theWord; } // accessor
string getWordC() { return theWordC; } // accessor
private:
string words;
vector<string> allWords;
ifstream file;
string pone; // player one's name
int random;
string theWord; // chosen word
string theWordC; // consealed chosen word
char letter;
int tries;
int time;
};
int main()
{
bool cont = 1;
srand((unsigned)time(0));
hangman game;
game.readWords();
game.setWord();
while (cont)
{
game.promptUser();
}
char f;
cin >> f;
return 0;
}
hangman::hangman() : tries(0), time(60)
{
std::cout << "Player one, enter your name: ";
std::cin >> pone;
}
void hangman::readWords()
{
file.open("words.txt");
if (!file )
{
cout << "Unable to open file";
}
while (file >> words )
{
allWords.push_back(words);
}
file.close();
}
void hangman::setWord()
{
random = (rand()%10)+1; // 1 - 10
for ( int i = 0; i != random; i++)
{
theWord = allWords[random];
}
}
void hangman::promptUser()
{
string temp(theWord.size(), '_');
theWordC = temp;
cout << "TRIES: " << tries << "\t" << "TIME LEFT: " << time << endl;
cout << "WORD SO FAR: " << theWordC << endl;
cout << pone << ", guess a letter: ";
cin >> letter;
tries++;
for ( int i = 0; i != theWord.size(); i++ )
{
if ( letter == theWord[i] )
{
theWordC[i] = letter;
}
}
if (theWordC == theWord)
{
cout << "Congratulations !, you win :)" << endl;
}
}
Firstly please make a file called "words.txt" and place it in the same folder as the program, In the file make sure there are at least 10 words seperated on each different line then finally run the program and you will see that the string that's concealing the word isn't showing the characters that have been gueesed for some reason.
