Reputation: 9
#include <iostream>
#include <string>//needed to make string array
#include <fstream>//Needed for redaing in from external file
#include <cstdlib>//needed for rand() function (for random word)
#include <ctime>//needed for time() funtion to seed rand()
using namespace std;
/*
April 25,2020
This program will take read in a random word from an external file and use it for a game of hang man */
void greeting();
void wordPick();
int main()
{
char playAgain;
int tries;
char playerGuess;
string secretWord;
greeting();
ifstream inFile("randwords.txt");
if (inFile.is_open())
{
string wordlist[10];
for(int i = 0; i < 10; ++i)
{
inFile >> wordlist[i];
}
srand(time(0));
string secretword = wordlist[rand() % 10];
cout << secretword << endl;
inFile.close();
}
//wordPick();
//ask user to guess a letter
cout << "Please guess a letter: " << endl;
cin >> playerGuess;
if (playerGuess == secretWord[0])
{
cout << "Thats correct!" << secretWord [0];
}
else if (playerGuess == secretWord[1])
{
cout << "thats correct!" << secretWord[1];
}
else if (playerGuess == secretWord[2])
{
cout << "Thats correct!" << secretWord[2];
}
cout << "Do you want to play again? Y or N: ";
cin >> playAgain;
while (playAgain != 'Y' && playAgain != 'y' && playAgain != 'N' && playAgain != 'n')
{
cout << "Invalid, please enter Y or N: ";
cin >> playAgain;
}
return 0;
}
void wordPick()//reads in external file and puts it in an array for a library of words to randomly choose
{
ifstream inFile("randwords.txt");
if (inFile.is_open())
{
string wordlist[10];
for(int i = 0; i < 10; ++i)
{
inFile >> wordlist[i];
}
srand(time(0));
string secretword = wordlist[rand() % 10];
// cout << secretword << endl;
inFile.close();
}
}
void greeting()//welcomes the player to the game and starts the game
{
string name;
cout << "Hello, Player welcome to Hangman! " << endl;
cout << "What should I call you?" << endl;
cin >> name;
cout << "Hello " << name << ", in this game you will try to guess a random 3 letter word." << endl;
cout << "You will have at least 6 ties to guess the word or else the drawing will complete. Good luck!" << endl;
What I am attempting to do is to check if the char playerGuess
is one of the characters in string secretWord
, but it isn't outputting the letter even if it is correct. Maybe there is an easier way to compare that I'm just missing?
I thought since this still compares that it should work, but it's just ending the program after guessing the letter.
Upvotes: 0
Views: 47
Reputation: 75062
You assigned the randomly chosen word to secretword
(with small w
), but the judge is based on secretWord
(with large W
), to which no word is assigned.
The part
string secretword = wordlist[rand() % 10];
cout << secretword << endl;
should be
secretWord = wordlist[rand() % 10];
cout << secretWord << endl;
Also note that you mustn't declare secretWord
in the if
block, or the assignment won't be visible to the judge part.
Upvotes: 1