I have started with C++ and I am in the middle of creating a hangman game, My code worked fine up until I chose to make three different levels of difficulty, My game asks the user for the difficulty level they would like to play, then instead of actually playing the game, it skips straight to the end where it says the user has guessed the word correctly. Any help appreciated!
The code is as follows :
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cctype>
using namespace std;
void ClearScreen();
void DisplayMan0();
void DisplayMan1();
void DisplayMan2();
void DisplayMan3();
void DisplayMan4();
void DisplayMan5();
void DisplayMan6();
void DisplayMan7();
int main()
{
const int MAX_WRONG = 7; // incorrect guesses allowed
void (*pfnaDisplayMan[])() = {DisplayMan0, DisplayMan1, DisplayMan2, DisplayMan3, DisplayMan4, DisplayMan5, DisplayMan6, DisplayMan7};
vector<string> words; // Level 1
words.push_back("GREEN");
words.push_back("BANANA");
words.push_back("LAPTOP");
words.push_back("GIRAFFE");
words.push_back("PENCIL");
vector<string> wordsD1; // Level 2
wordsD1.push_back("DELICIOUS");
wordsD1.push_back("COMPUTING");
wordsD1.push_back("SOFTWARE");
wordsD1.push_back("HARDWARE");
wordsD1.push_back("TELEPHONE");
vector<string> wordsD2; // Level 3
wordsD2.push_back("BAMBOOZLED");
wordsD2.push_back("DAYDREAMER");
wordsD2.push_back("CANNIBALISM");
wordsD2.push_back("NERVOUSLY");
wordsD2.push_back("APPROACHING");
srand((unsigned int)time(0));
string THE_WORD;
string soFar;
int wordLength;
string used; // letters already guessed
cout << "\t\t HANGMAN\n";
cout << "Please enter a difficulty level [1-3] ";
int dif = 0;
while(dif < 1 || dif > 3)
{
cin >> dif;
}
cout << "You have chosen difficulty level : "<< dif << endl;
if(dif == 1)
{
random_shuffle(words.begin(), words.end());
int incorrectGuesses = 0; // number of incorrect guesses
string const THE_WORD = words[0]; // word to guess
string soFar(THE_WORD.size(), '*'); // word guessed so far
// count length of randomly chosen string and display it
wordLength = THE_WORD.length();
}
if(dif == 2)
{
random_shuffle(wordsD1.begin(), wordsD1.end());
int incorrectGuesses = 0; // number of incorrect guesses
string const THE_WORD = wordsD1[0];
string soFar(THE_WORD.size(), '*');
wordLength = THE_WORD.length();
}
if(dif == 3)
{
random_shuffle(wordsD2.begin(), wordsD2.end());
int incorrectGuesses = 0; // number of incorrect guesses
string const THE_WORD = wordsD2[0];
string soFar(THE_WORD.size(), '*');
wordLength = THE_WORD.length();
}
// main loop
while ((incorrectGuesses < MAX_WRONG) && (soFar != THE_WORD))
{
cout << "\n- There are : "<< wordLength <<" letters in the word :\t" << soFar << endl;
cout << "\n- You have guessed " <<incorrectGuesses << " times wrong out of "<< MAX_WRONG << " allowed wrong guesses.\n";
cout << "\nLetters used : " << used << endl;
cout << "=====================================================";
char guess;
cout << "\n\t\tEnter a letter : ";
cin >> guess;
guess = toupper(guess); //make uppercase since secret word in uppercase
while (used.find(guess) != string::npos)
{
cout << "\nYou've already guessed the letter " << guess << endl;
cout << "Enter another letter / word: ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
if (THE_WORD.find(guess) != string::npos)
{
cout << "=====================================================\n";
cout << "- Correct, The letter " << guess << " is in the word.\n";
// update soFar to include 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";
++incorrectGuesses;
pfnaDisplayMan[incorrectGuesses]();
}
}
// shut down
if (incorrectGuesses == MAX_WRONG)
cout << "\nYou've been hanged!";
else
cout << "\nYou guessed it!";
cout << "\nThe word was " << THE_WORD << endl;
return 0;
}
void DisplayMan0()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan1()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan2()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan3()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan4()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X\\" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan5()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X\\" << endl;
cout << "| /" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan6()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X\\" << endl;
cout << "| / \\" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan7()
{
using namespace std;
cout << "\t\t_______" << endl;
cout << "\t\t|DONT" << endl;
cout << "\t\t|HANG" << endl;
cout << "\t\t|THE" << endl;
cout << "\t\t|MAN" << endl;
cout << "\t\t| O" << endl;
cout << "\t\t| _______ /XL" << endl;
cout << "\t\t__|_____| / \\" << endl;
}
Put incorrectGuesses out of those scopes. Because out of those scopes this variable is not declared.
if(dif == 1)
{
int incorrectGuesses = 0;
...
}
if(dif == 2)
{
int incorrectGuesses = 0;
...
}
if(dif == 3)
{
int incorrectGuesses = 0;
...
}
Should be
int incorrectGuesses = 0;
if(dif == 1)
{
...
}
if(dif == 2)
{
...
}
if(dif == 3)
{
...
}
Same issues for soFar, THE_WORD and wordLength. That part of code should be like this:
string THE_WORD;
string soFar;
int wordLength;
string used;
// cout ... cin ....
int incorrectGuesses = 0;
if(dif == 1)
{
random_shuffle(words.begin(), words.end());
THE_WORD = words[0]; // word to guess
wordLength = THE_WORD.length();
}
if(dif == 2)
{
random_shuffle(wordsD1.begin(), wordsD1.end());
THE_WORD = wordsD1[0];
wordLength = THE_WORD.length();
}
if(dif == 3)
{
random_shuffle(wordsD2.begin(), wordsD2.end());
THE_WORD = wordsD2[0];
wordLength = THE_WORD.length();
}
soFar.assign(THE_WORD.size(), '*');
M M. is correct. Your redeclaring the variables.
Just a small remark. I would use a Switch Case instead of a set of if statements. Changing:
if(dif==1){}
if(dif==2){}
if(dif==3){}
into
switch(dif){
case(1):
break;
case(2):
break;
case(3):
break;
}
Not for necessarily for readability but more to indicate that the value of dif isn't edited depending upon its value. For example:
Option 1:
dif = 1;
if(dif==1){ dif = 3; }
if(dif==2){}
if(dif==3){ dif = 7; }
Versus:
Option 2
dif = 1;
switch(dif){
case(1):
dif = 3;
break;
case(2):
break;
case(3):
dif = 7;
break;
}
Option 1 output: 7
Option 2 output: 3
You declare incorrectGuesses out of scope. It is NEVER declared or assigned a value. Declare it at the beginning of your function and assign it value in the other scopes.
Related
Im writing a wordle game and am trying to get the output to work, but i have no clue as to what im doing wrong here. The basic version of the code is 5 letter words are taken from a word file and stored in an array, then a random word is picked from there to be the answer to the wordle. Then the user is prompted for input and once they input a word, it verifies the length, as well as if it is in the array of words. then another function takes the guessed word and compares it against the winning word and outputs the guessed word with colors to show what letters are in the right spot, like real wordle. The issue arises when i try to print everything out, i tried to use a while loop to ask for input but i couldnt get it to work so i decided to test it by making a function that asks for the input, then i called it six times, each time giving it a different variable to store the result in, then print out the first one on the first guess, the first and second on the second guess, and so on. But it only prints out the current guess. It might be something very obvious but i have spent so much time coding i have no idea. any help is greatly appreciated.
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
using namespace std;
const string CORRECT = "\033[7;32m";
const string CLOSE = "\033[7;33m";
const string INCORRECT = "\033[7;37m";
const string END = "\033[0m";
int verifyExists(string word, string verifyArr[2315]) {
if (word.size() == 5)
{
for (int i = 0; i < 2315; i++)
{
if (word == verifyArr[i])
{
return 1;
}
}
return 2;
} else {
return 3;
}
}
string buildResult(string plyrGuess, string word)
{
string result[5];
string color;
for (int i = 0; i < 5; i++){
if (plyrGuess[i] != word[i])
{
color = INCORRECT + plyrGuess[i] + END;
result[i] = color;
}
if ((plyrGuess[i] != word[i]) && (plyrGuess[i] == word[0] || plyrGuess[i] == word[1] || plyrGuess[i] == w\
ord[2] || plyrGuess[i] == word[3] || plyrGuess[i] == word[4]))
{
color = CLOSE + plyrGuess[i] + END;
result[i] = color;
}
if (plyrGuess[i] == word[i])
{
color = CORRECT + plyrGuess[i] + END;
result[i] = color;
}
}
string done;
for (int i = 0; i < 5; i++)
{
cout << result[i];
}
getline(cin, done);
return done;
}
string askInput(string array[2315])
{
string guessWord;
cout << "What word would you like to guess?" << endl;
getline(cin, guessWord);
while (verifyExists(guessWord, array) == 2)
{
cout << "The word: " << guessWord << " is not in the word list" << endl;
getline(cin, guessWord);
}
while (verifyExists(guessWord, array) == 3)
{
cout << "You must enter a word that is 5 letters in length: " << endl;
getline(cin, guessWord);
}
return guessWord;
}
void playGame(string winWord, string arr[2315]) {
cout << "Ok. I am thinking of a word with 5 letters." << endl;
string guess1 = askInput(arr);
string done1 = buildResult(guess1, winWord);
cout << done1 << "\n" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess2 = askInput(arr);
string done2 = buildResult(guess2, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess3 = askInput(arr);
string done3 = buildResult(guess3, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess4 = askInput(arr);
string done4 = buildResult(guess4, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << done4 << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess5 = askInput(arr);
string done5 = buildResult(guess5, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << done4 << endl;
cout << "_____" << endl;
string guess6 = askInput(arr);
string done6 = buildResult(guess6, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << done4 << endl;
cout << done5 << endl;
cout << done6 << endl;
}
int main() {
string wordArray[2315];
ifstream myfile ("proj1_data.txt");
cout << " Welcome to UMBC Wordle" << endl;
if (myfile.is_open())
{
string word;
int loop = 0;
while (getline(myfile, word))
{
wordArray[loop++] = word;
}
cout << " " << endl;
cout << " Your file was imported!" << endl;
cout << " 2315 Words imported" << endl;
cout << " " << endl;
myfile.close();
}
srand(time(0));
string chosenWord = wordArray[rand() % 2315];
playGame(chosenWord, wordArray);
return 0;
}
I dont get any errors when i compile it so i know that nothings "wrong" with the code, the problem is in the playGame function, i included the whole code in case that helps
I am writing in C++ and the errors I am having are:
E0120 return value type does not match the function type
C4700 uninitialized local variable 'name' used
C2562 interact 'void function returning a value
And a warning error of C4447.
My code is down below:
#include <limits>
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
void readFile(char sudokuBoard[][9]);
void writeFile(char sudokuBoard[][9]);
void display(char sudokuBoard[][9]);
void interact();
void getOption(char sudokuBoard[][9]);
void editSquare(char sudokuBoard[][9]);
void showValues();
void openingMessage();
void openingQuestion();
//opening message to the game and pause
void openingMessage()
{
std::cout << "Welcome to Sudoku"
<< endl << "Press any key to continue.";
cin.ignore();
}
//Questions to determine whether the user will play the game
void openingQuestion()
{
char response; // users input to the question below
cout << "Would you like to play Sudoku ? " << endl << "1 for yes, 2 for no";
cin >> response;
if (response == 1) //if there answer is yes
{
//return main();
}
else if (response == 2) //if answer is no
{
cout << "are you sure you do not want to play ?" << endl << "1 for yes and 2 for no";
//if user answers no
char eResponse; //response to the next question
if (eResponse == 2) // 2 equals no
{
return main();
}
// if user answers yes
if (eResponse == 1) // 1 equals yes
{
//return exit();
}
}
}
//Makes other functions function
int main()
{
//Declaring array
char sudokuBoard[9][9];
//calling the other functions
readFile(sudokuBoard);
interact();
display(sudokuBoard);
return 0;
}
//Asks the user for a fulename to read a gamebaord
//in from that file name and then places it in an array
void readFile(char sudokuBoard[][9])
{
//Declare filename
char sourceFile[256];
//Declaring file input
ifstream fin;
//Getting the filename from the user
cout << "Where is your board located? ";
cin >> sourceFile;
//Open file error checking
fin.open(sourceFile);
if (fin.fail())
{
cout << "Input file opening failed. " << endl;
exit(1);
}
//Read file into array
for (int col = 0; col < 9; col++)
{
for (int row = 0; row < 9; row++)
{
fin >> sudokuBoard[row][col];
if (sudokuBoard[row][col] == '0')
{
sudokuBoard[row][col] = ' ';
}
}
}
//close the file
fin.close();
}
//displays the result to the screen
void display(char sudokuBoard[][9])
{
//Declare variables
char option;
//Display Column Title
cout << " A| B| C| D| E| F| G| H| I" << endl;
//Row 1
cout << "1 "
<< sudokuBoard[0][0]
<< " " << sudokuBoard[1][0]
<< " " << sudokuBoard[2][0]
<< "|"
<< sudokuBoard[3][0]
<< " " << sudokuBoard[4][0]
<< " " << sudokuBoard[5][0]
<< "|"
<< sudokuBoard[6][0]
<< " " << sudokuBoard[7][0]
<< " " << sudokuBoard[8][0]
<< endl;
//Row 2
cout << "2 "
<< sudokuBoard[0][0]
<< " " << sudokuBoard[1][1]
<< " " << sudokuBoard[2][1]
<< "|"
<< sudokuBoard[3][1]
<< " " << sudokuBoard[4][1]
<< " " << sudokuBoard[5][1]
<< "|"
<< sudokuBoard[6][1]
<< " " << sudokuBoard[7][1]
<< " " << sudokuBoard[8][1]
<< endl;
//Row 3
cout << "3 "
<< sudokuBoard[0][2]
<< " " << sudokuBoard[1][2]
<< " " << sudokuBoard[2][2]
<< "|"
<< sudokuBoard[3][2]
<< " " << sudokuBoard[4][2]
<< " " << sudokuBoard[5][2]
<< "|"
<< sudokuBoard[6][2]
<< " " << sudokuBoard[7][2]
<< " " << sudokuBoard[8][2]
<< endl;
//Separator
cout << " -----_-----_-----" << endl;
//Row 4
cout << "4 "
<< sudokuBoard[0][3]
<< " " << sudokuBoard[1][3]
<< " " << sudokuBoard[2][3]
<< "|"
<< sudokuBoard[3][3]
<< " " << sudokuBoard[4][3]
<< " " << sudokuBoard[5][3]
<< "|"
<< sudokuBoard[6][3]
<< " " << sudokuBoard[7][3]
<< " " << sudokuBoard[8][3]
<< endl;
//Row 5
cout << "5 "
<< sudokuBoard[0][4]
<< " " << sudokuBoard[1][4]
<< " " << sudokuBoard[2][4]
<< "|"
<< sudokuBoard[3][4]
<< " " << sudokuBoard[4][4]
<< " " << sudokuBoard[5][4]
<< "|"
<< sudokuBoard[6][4]
<< " " << sudokuBoard[7][4]
<< " " << sudokuBoard[8][4]
<< endl;
//Row 6
cout << "6 "
<< sudokuBoard[0][5]
<< " " << sudokuBoard[1][5]
<< " " << sudokuBoard[2][5]
<< "|"
<< sudokuBoard[3][5]
<< " " << sudokuBoard[4][5]
<< " " << sudokuBoard[5][5]
<< "|"
<< sudokuBoard[6][5]
<< " " << sudokuBoard[7][5]
<< " " << sudokuBoard[8][5]
<< endl;
//Separator
cout << " -----_-----_-----" << endl;
//Row 7
cout << "7 "
<< sudokuBoard[0][6]
<< " " << sudokuBoard[1][6]
<< " " << sudokuBoard[2][6]
<< "|"
<< sudokuBoard[3][6]
<< " " << sudokuBoard[4][6]
<< " " << sudokuBoard[5][6]
<< "|"
<< sudokuBoard[6][6]
<< " " << sudokuBoard[7][6]
<< " " << sudokuBoard[8][6]
<< endl;
//Row 8
cout << "8 "
<< sudokuBoard[0][7]
<< " " << sudokuBoard[1][7]
<< " " << sudokuBoard[2][7]
<< "|"
<< sudokuBoard[3][7]
<< " " << sudokuBoard[4][7]
<< " " << sudokuBoard[5][7]
<< "|"
<< sudokuBoard[6][7]
<< " " << sudokuBoard[7][7]
<< " " << sudokuBoard[8][7]
<< endl;
cout << "9 "
<< sudokuBoard[0][8]
<< " " << sudokuBoard[1][8]
<< " " << sudokuBoard[2][8]
<< "|"
<< sudokuBoard[3][8]
<< " " << sudokuBoard[4][8]
<< " " << sudokuBoard[5][8]
<< "|"
<< sudokuBoard[6][8]
<< " " << sudokuBoard[7][8]
<< " " << sudokuBoard[8][8]
<< endl
<< endl;
getOption(sudokuBoard);
}
//Allows the user to interact and manipulate the game board
void interact()
{
cout << "Options:" << endl
<< " ? Show these instructions" << endl
<< " D Display the board" << endl
<< " X Edit one square" << endl
<< " H Help show the possible values for one of the squares"
<< endl
<< " Q Save and Quit" << endl
<< endl;
return getOption;
}
//gets the user's input
void getOption(char sudokuBoard[][9])
{
char option;
cout << "> ";
cin >> option;
if (option == 'x' || option == 'X')
editSquare(sudokuBoard);
else if (option == '?')
interact();
else if (option == 'd' || option == 'D')
display(sudokuBoard);
else if (option == 'h' || option == 'H')
showValues();
else if (option == 'q' || option == 'Q')
writeFile(sudokuBoard);
else
cout << "ERROR: Invalid command";
return;
}
//edits one square with coordinates entered by the user
void editSquare(char sudokuBoard[][9])
{
//Declare variables
char letter;
int number;
int value = 0;
//Get letter and number coordinates
cout << "What are the coordinates of the square: ";
cin >> letter >> number;
//Converts letter to uppercase
letter = toupper(letter);
//if square is full, display "read only" message
if (sudokuBoard[letter - 65][number - 1] != ' ')
{
cout << "ERROR: square \'" << letter
<< number << "\' is a read-only" << endl;
getOption(sudokuBoard);
}
else
{
//get value to place in the coordinates
cout << "what is the value at \'" << letter
<< number << "\': ";
cin >> value;
//makes sure value is within the right range
if (value < 1 || value > 9)
{
cout << "Try Again: Value |'" << value << "| in square |'"
<< letter << number << "|' is invalud" << endl;
cout << endl;
getOption(sudokuBoard);
}
// Check for duplicate in column
for (int row = 0; row < 9; ++row)
if (sudokuBoard[row][number - 1] == value)
{
cout << "ERROR: square \'" << letter
<< number << "\' you typed a duplicate number" << endl
<< "Please try again" << endl;
}
// Check for duplicate in row
for (int col = 0; col < 9; ++col)
if (sudokuBoard[letter - 65][col] == value)
{
cout << "ERROR: square \'" << letter
<< number << "\' you typed a duplicate number" << endl
<< "Please try again" << endl;
}
cout << endl;
sudokuBoard[letter - 65][number - 1] = value;
getOption(sudokuBoard);
}
return;
}
//writes the content of the board to a file to be picked up later
void writeFile(char sudokuBoard[][9])
{
//File output
ofstream fout;
char destinationFile[256];
//user input
cout << "What file would you like to write your board to: ";
cin >> destinationFile;
//Open destination file & error checking
fout.open(destinationFile);
if (fout.fail())
{
cout << "Output file opening failed" << endl;
exit(1);
}
else
cout << "Board written successfully";
//Write board to file
for (int col = 0; col < 9; col++)
{
for (int row = 0; row < 9; row++)
{
if (sudokuBoard[row][col] == ' ')
{
sudokuBoard[row][col] = '0';
}
fout << sudokuBoard[row][col];
//Makes sure it's a 9x9 grid
if (row % 9 == 0)
{
fout << endl;
}
}
}
//close file
fout.close();
}
//Show all the possible values for a given coordinates
void showValues()
{
//variables
char letter;
int number;
//letter/number coordinates
cout << "What are the coordinates of the square: ";
cin >> letter >> number;
//Coinverts letter to uppercase
letter = toupper(letter);
return;
}
I am using Visual Studio 2019 for this.
A couple notes to point out
first of all, you can not return the main function
in your line
if (eResponse == 2) // 2 equals no
{
return main();
}
next
you have a lot of void function with return statements
because the function is void you can not return anything
instead of
void getOption(char sudokuBoard[][9])
{
char option;
cout << "> ";
cin >> option;
if (option == 'x' || option == 'X')
editSquare(sudokuBoard);
else if (option == '?')
interact();
else if (option == 'd' || option == 'D')
display(sudokuBoard);
else if (option == 'h' || option == 'H')
showValues();
else if (option == 'q' || option == 'Q')
writeFile(sudokuBoard);
else
cout << "ERROR: Invalid command";
return;
}
use
char getOption(char sudokuBoard[][9])
{
char option;
cout << "> ";
cin >> option;
if (option == 'x' || option == 'X')
editSquare(sudokuBoard);
else if (option == '?')
interact();
else if (option == 'd' || option == 'D')
display(sudokuBoard);
else if (option == 'h' || option == 'H')
showValues();
else if (option == 'q' || option == 'Q')
writeFile(sudokuBoard);
else
cout << "ERROR: Invalid command";
return option;
}
go through your functions and ask yourself, do i need to return a value? if yes then change from void to what ever type you are using and if no then remove the return statement.
for your warning issue
char sudokuBoard[9][9];
is not being initialised.
you can do something like
char sudokuBoard[9][9] = {};
Program's Aim:
The program is a hangman game which get a list of planets from our solar system, saves it to an array then randomly selects one word from the array and subsequently prints two letters of the word on the board. The program runs perfectly in a windows environment, but fails in runtime on linux.
Problem:
The program replaces the first character in the output stream with the last character of that stream. That happens when printing the word on the board and also when the word is displayed when it is correctly or wrongly guessed.
e.g.:
word = Mars
For 6 wrong guess it's supposed to print, Too bad you didn't guess right. It was "mars".
Instead, it prints: "oo bad you didn't guess right. It was "mars
Here are the files:
wordlist.yx:
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Pluto
Hangman.h:
#pragma once
#include <iostream>
using namespace std;
// Check for OS
#ifdef _WIN32
#define SYS "MS"
#else
#define SYS "LINUX"
#endif
class Hangman {
private:
int version = 3;
string release_date = "01/05/2016";
int &v = version;
string &r = release_date;
static const int WORDLIST_SIZE = 10;
string wordlist[WORDLIST_SIZE];
string word, hidden_word, wordfile = {"wordlist.yx"};
int word_length, tries_left;
bool is_match;
public:
Hangman();
~Hangman();
//attributes
string user_input, arch;
char choice;
// Game functionality methods
void printMenu(Hangman &);
void info(Hangman &) const;
void startGame(Hangman &);
void reset();
void getWordlist();
void getWordAndSetHidden();
int getTries();
void printHangman(int);
void printBoard();
void getInput(Hangman &);
int validateInput(char);
void decideFate(Hangman &);
void decision(Hangman &);
// Invalid input and screen clearing methods
void invalidInput1(Hangman &, char &);
void invalidInput2(Hangman &, string &);
void cls() const;
};
Hangman.cpp:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <limits>
#include <algorithm>
#include <string>
#include "Hangman.h"
using namespace std;
//Constructor
Hangman::Hangman(){
//Get's OS
// Microsoft
if(SYS == "MS"){
arch = "cls";
} else{
//linux, unix, OSX
arch = "clear";
}
hidden_word = "";
tries_left = 6;
}
// De-constructor
Hangman::~Hangman(){
//Destroy objects
}
// Menu Options
void Hangman::printMenu(Hangman &s){
cls();
cout << " _____Hangman (v7)_____ " << endl;
cout << "| |" << endl;
cout << "| Play - P |" << endl;
cout << "| Info - I |" << endl;
cout << "| Quit - Q |" << endl;
cout << "------------------------" << endl;
cout << "Choice: ";
getline(cin, user_input);
// Pass first character of string to char
choice = user_input[0];
switch(choice){
case 'p':
case 'P':
startGame(s);
break;
case 'i':
case 'I':
info(s);
break;
case 'q':
case 'Q':
cls();
cout << "Thank you for playing..." << endl;
exit(EXIT_SUCCESS);
break;
default:
invalidInput1(s, choice);
}
}
void Hangman::info(Hangman &m) const{
string ic;
cls();
cout << "+--------------------------------------------------------------------+\n"
<< "| Hangman Instructions |\n"
<< "+--------------------------------------------------------------------+\n"
<< "| This Hangman game is played by entering a guessed letter at a time.|\n"
<< "| 6 wrong guesses are given by default and decrements by 1 (one) on |\n"
<< "| each wrong guess. |\n"
<< "+--------------------------------------------------------------------+\n"
<< "| In-game options |\n"
<< "+--------------------------------------------------------------------+\n"
<< "| restart - Start a new game |\n"
<< "| menu - Display main menu |\n"
<< "| quit - Exit game |\n"
<< "+--------------------------------------------------------------------+\n"
<< "| Game Information |\n"
<< "+--------------------------------------------------------------------+\n"
<< "| Version: " << v << " |\n"
<< "| Date: " <<r<< " |\n"
<< "+--------------------------------------------------------------------+\n"
<< "| Author |\n"
<< "+--------------------------------------------------------------------+\n"
<< "| Philan James (Zoutiyx) |\n"
<< "| zoutiyx#gmail.com |\n"
<< "+--------------------------------------------------------------------+\n\n";
cout << "Press enter to close... ";
getline(cin, ic);
m.printMenu(m);
}
void Hangman::startGame(Hangman &h){
cls();
h.reset();
h.getWordlist();
h.getWordAndSetHidden();
h.decideFate(h);
do {
h.printHangman(h.getTries());
h.printBoard();
h.getInput(h);
h.decideFate(h);
} while(h.getTries() != 0);
}
//Gets the wordlist from a file and stores it into an array
void Hangman::getWordlist(){
fstream in_words(wordfile, ios::in);
if(!in_words.is_open()){
cerr << "Error 0: " << wordfile << " isn't found in current directory!\n";
} else{
for(int i = 0; (i < WORDLIST_SIZE - 1) && !in_words.eof(); i++){
getline(in_words, *(wordlist + i), '\n');
}
}
in_words.close();
}
void Hangman::getWordAndSetHidden(){
srand(time(NULL));
int word_index, p1, p2;
word_index = rand() % (WORDLIST_SIZE - 1) + 0;
word = wordlist[word_index];
// Sets the hidden word letters to underscores
for(unsigned int i = 0; i < word.length(); i++){
if(word[i] == ' ') {
hidden_word.push_back(' ');
} else {
hidden_word.push_back('_');
}
}
//selecting the random two indexes of the word
p1 = rand() % word.length();
p2 = rand() % word.length();
while (p1 == p2 || p2 == p1){
p1 = rand() % word.length();
p2 = rand() % word.length();
}
// Assigning the letter to the corresponding index
for(int i = 0; i < (int)word.length(); i++){
if (i == p1){
hidden_word[i] = word[i];
} else if( i == p2){
hidden_word[i] = word[i];
}
// If a certain letter is the same as the on at the p1 or p2,
// It is also printed on the board, making it more than (2) default letters
if (tolower(word[p1]) == tolower(word[i])){
hidden_word[i] = word[i];
}
if (tolower(word[p2]) == tolower(word[i])){
hidden_word[i] = word[i];
}
}
}
// Get lives remaining
int Hangman::getTries(){
return tries_left;
}
// Print's hangman state based on lives left
void Hangman::printHangman(int ll){
cls();
cout << "Planets in our solor system...\n\n";
cout << "Tries left: " << tries_left << endl;
switch (ll){
case 6:
cout << " |----| " << endl;
cout << " | " << endl;
cout << " | " << endl;
cout << " | " << endl;
cout << " | " << endl;
cout << "____|____ " << endl;
cout << endl;
break;
case 5:
cout << " |----| " << endl;
cout << " | 0 " << endl;
cout << " | " << endl;
cout << " | " << endl;
cout << " | " << endl;
cout << "____|____ " << endl;
cout << endl;
break;
case 4:
cout << " |----| " << endl;
cout << " | 0 " << endl;
cout << " | | " << endl;
cout << " | | " << endl;
cout << " | " << endl;
cout << "____|____ " << endl;
cout << endl;
break;
case 3:
cout << " |----| " << endl;
cout << " | 0 " << endl;
cout << " | /| " << endl;
cout << " | | " << endl;
cout << " | " << endl;
cout << "____|____ " << endl;
cout << endl;
break;
case 2:
cout << " |----| " << endl;
cout << " | 0 " << endl;
cout << " | /|\\ " << endl;
cout << " | | " << endl;
cout << " | " << endl;
cout << "____|____ " << endl;
cout << endl;
break;
case 1:
cout << " |----| " << endl;
cout << " | 0 " << endl;
cout << " | /|\\ " << endl;
cout << " | | " << endl;
cout << " | / " << endl;
cout << "____|____ " << endl;
cout << endl;
break;
case 0:
cout << " |----| " << endl;
cout << " | 0 " << endl;
cout << " | /|\\ " << endl;
cout << " | | " << endl;
cout << " | / \\ " << endl;
cout << "____|____ " << endl;
cout << endl;
break;
}
}
// Display hidden word
void Hangman::printBoard(){
for(unsigned int i = 0; i < hidden_word.length(); i++){
if(word[i] == ' '){
cout << word[i];
} else if(i != hidden_word.length()){
cout << hidden_word[i] << " ";
} else{
cout << hidden_word[i];
}
}
cout << endl << endl;
}
// Get letter choice and assign position 0 to character
void Hangman::getInput(Hangman &c){
cout << "Letter choice: ";
getline(cin, user_input);
transform(user_input.begin(), user_input.end(),
user_input.begin(), ::tolower);
if(user_input == "restart"){
c.reset();
c.startGame(c);
} else if(user_input == "menu"){
printMenu(c);
} else if(user_input == "quit"){
cout << "\nThank you for playing...\n";
exit(EXIT_SUCCESS);
} else{
choice = user_input[0];
user_input = "";
validateInput(choice);
}
}
// test character for validity
int Hangman::validateInput(char choice){
for(unsigned int i = 0; i < hidden_word.length(); i++){
//Checks if entered character is already on the board
if(toupper(choice) == hidden_word[i] || tolower(choice) == hidden_word[i]){
--tries_left;
return 0;
}
// Checks if character is a valid input
if(toupper(choice) == word[i] || tolower(choice) == word[i]){
hidden_word[i] = word[i];
is_match = true;
}
// If end of loop and character is invalid, lives left -=1
if(i == hidden_word.length() -1 && is_match != true){
--tries_left;
return 0;
}
}
is_match = false;
return 0;
}
// Checks if the word was found or not
void Hangman::decideFate(Hangman &f){
if(hidden_word == word){
cls();
cout << "Congrats, \"" << word << "\" it is.\n\n";
f.decision(f);
}
if(tries_left == 0 && hidden_word != word){
cin.ignore();
f.printHangman(f.getTries());
cout << "Too bad you didn't guess right. It was \""
<< word << "\"" << endl << endl;
f.decision(f);
}
}
void Hangman::decision(Hangman &c) {
cout << "+----------------------+" << endl;
cout << "| Alternatives |" << endl;
cout << "+----------------------+" << endl;
cout << "\"restart\" or a new game\n"
<< "\"help\" for help information\n"
<< "\"quit\" to exit\n\nChoice: ";
getline(cin, user_input);
transform(user_input.begin(), user_input.end(),
user_input.begin(), ::tolower);
if(user_input == "restart"){
c.startGame(c);
} else if(user_input == "help"){
info(c);
} else if(user_input == "quit"){
cls();
cout << "Thank you for playing..." << endl;
exit(EXIT_SUCCESS);
} else{
invalidInput2(c,user_input);
}
}
void Hangman::invalidInput1(Hangman &i1, char &i){
//cin.clear();
cerr << "' " << i << " ' is not a valid input."
<< " Press <Enter> to try again.";
getline(cin, user_input);
Hangman::printMenu(i1);
}
void Hangman::invalidInput2(Hangman &i2, string &i){
//cin.clear();
cerr << "\" " << i << " \" is not a valid input."
<< " Press <Enter> to try again.";
getline(cin, user_input);
cls();
Hangman::decision(i2);
}
// Reset game
void Hangman::reset(){
tries_left = 6;
hidden_word = "";
}
// Calls clear screen command
void Hangman::cls() const{
// passes cls or clear string as character pointer
system(arch.c_str());
}
main.cpp:
#include "Hangman.h"
int main() {
Hangman hangman;
hangman.printMenu(hangman);
}
Tried:
Running the program in a lower standard (11) from 14.
Online compiler from tutorialspoint.
Manually setting the word.
Observation:
I observed that if I manually set the word, that situation is resolved. How do I narrow in on this issue further?
Edit:
Added wordlist and removed a stray backslash which prevented compiling..
Try running dos2unix on your wordlist.yx file. If it was created on Windows, the newlines are probably \r\n, not just \n. And if that \r is interpreted literally, that will return to the beginning of the line prior to continuing to output to cout, thus overwriting your first character.
Reference to dos2unix can be found here.
To avoid using dos2unix, you could strip the \r characters from your wordlist array. One approach would be to loop through each word in the array and processing them like so:
currWord.erase( std::remove(currWord.begin(), currWord.end(), '\r'), currWord.end() );
I am trying to do a hangman project, but my code isn't working. Whenever I put in the proper letter, the code tells me it is wrong (even though it is right). Not really sure why - the code worked at some point but I changed some things and now I don't know why it doesn't work. So it is probably a simple fix, but I am just not seeing it.
Any help would be very appreciated!
#include <iostream>
using namespace std;
int letterFill (char, string, string&);
int main()
{
string name;
int maxAttempts = 5;
int wrongGuesses;
char letter;
srand(time(0));
const string wordList[15] = { "hanukkah", "sparklers", "mistletoe", "menorah", "presents", "reindeer",
"kwanzaa", "snowman", "eggnog", "celebration", "yuletide", "resolution", "nutcracker", "ornaments", "gingerbread" };
string correctWord = wordList[rand() % 15];
string unknown(correctWord.length(),'*');
cout << correctWord << endl;
cout << "Welcome to a fun game of winter holiday hangman! What is your name? " << endl;
cin >> name;
cout << name <<", there are some simple things you should know about this game before you start playing!" << endl;
cout << "You will be trying to guess a randomly selected word by typing in ONE letter at a time " << endl;
cout << "You will have " << maxAttempts << " tries before losing the game " << endl;
cout << "And remember, all of the words are winter holiday related. Good luck " << name <<"!" << endl;
cout << "*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*" <<endl;
while (wrongGuesses == 0)
{
cout << "Guess a letter" << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 1)
{
cout << "You have 4 guesses left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 2)
{
cout << "You have 3 guesses left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 3)
{
cout << "You have 2 guesses left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 4)
{
cout << "You have 1 guess left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 5)
{
cout << "Sorry " << name << " you have made 5 wrong guesses!" << endl;
cout << "Game over. Click any key to exit. Play again soon :) " << endl;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
system("pause");
return 0;
}
int letterFill (char guessLetter, string mysteryWord, string& guessWord)
{
int x;
int matches=0;
int lengthWord=mysteryWord.length();
for (x = 0; x< lengthWord; x++)
{
if (guessLetter == mysteryWord[x])
return 0;
if (guessLetter == mysteryWord[x])
{
guessWord[x] = guessLetter;
matches++;
}
}
return matches;
}
You aren't updating the string guessWord in your int letterFill() function. As soon as you see a letter that matches you return without entering that second if statement.
I assume what you want is only to return after fully updating the guessWord, based on that what you want to do is iterate through the string, updating guessWord as you find matches and after your loop do a check
if(matches == 0) return 0;
else return matches;
Right now I am trying to get my scorecard to work for hangman. This is a game I can play as many times as I want and I want it to show my lowest score when I press 2 at the game menu. For some reason my logic isn't working. Can anyone help? I have attached the 3 sections of code necessary for this to work.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <fstream>
using namespace std;
int maxAttempts = 10; //max attempts possible
void poorStiff(int);
int wordFill(char, string, string&);
int main()
{
int intro;
int bodyPart = 0;
ifstream wordIn; //file stream read in
wordIn.open("WordList.txt"); //list of words used in this game
//if (!wordIn.good()) { std::cerr << "open failed.\n"; exit(1); }
char letter; //letter guessed
int numWrongGuesses = 0; //counts the number of wrong guesses
string theWord;
string words[13];
int play = 0;
bool run = true;
int makeYourSelection = 0;
int bestScore = 11;
while (run == true)
{
int attemptsGame = 0;
// put a game menu to loop that asks if you want to keep playing or exit and go to scorecard
cout << " WELCOME TO THE GAME OF HANGMAN\n\n\n\n";
cout << " Press 1 to play the game, press 2 to exit to the scorecard \n\n";
cout << " You have 10 attempts to guess the words before you get hung \n\n";
cin >> play;
while (play == 1)//loops while user has entered 1, 0 exits the game
{
for (int i = 0; i < 13; i++) //labeled 13 and not words because 13 is a constant
{
wordIn >> words[i];//replaces the file words and puts them in an array and counts them out of the file
cout << words[i] << endl;
}
srand(time(NULL));//to get a random word
int n = rand() % 12;
theWord = words[n]; //pulls word from file
wordIn.close();
string mystery(theWord.length(), '*'); //replaces word letters with asterisks
while (numWrongGuesses < maxAttempts) // while the amount of guesses is less than the max wrong guesses
{
cout << mystery << endl << endl;
cout << "You now have the length of the word represented by the *'s. \n\n";
cout << "Guess a letter \n\n";
cin >> letter;
if (wordFill(letter, theWord, mystery) == 0) //fuction call
{
bodyPart++;
poorStiff(bodyPart);
cout << "You have entered a letter that isn't in the word, guess again. \n\n";
numWrongGuesses++;
attemptsGame++;
}
else
{
for (int i = 0; i < mystery.length(); i++)
{
if (theWord[i] == letter)
{
mystery[i] = letter;
}
}
cout << "You have found one of the letters. Congratulations! \n\n";
cout << "You have: " << maxAttempts - numWrongGuesses;
cout << " guesses left \n\n" << endl;
}
if (theWord == mystery) // the word is the same as mystery
{
cout << theWord << endl;
cout << "\n\n Awesome, you guessed it. \n\n";
break;
if (attemptsGame < bestScore)
{
bestScore = attemptsGame;
}
}
}
if (numWrongGuesses == maxAttempts) //when you run out of guesses
{
cout << "Too bad, you ran out of guesses and have been hung at the gallows. \n\n";
cout << "The word you were trying to guess was " << theWord << endl;
poorStiff(bodyPart);
}
cin.ignore();
cin.get();
break;
}
while (play == 2)
{
cout << "Best Scores: \n\n";
cout << bestScore << endl;
system("pause");
return 0;
break;
}
}
system("pause");
return 0;
}
int wordFill(char guess, string theWordSecret, string&guessWord) //function for determing if you guess a letter contained
{
int i;
int hits = 0; //letter hits within the word
int many = theWordSecret.length();
for (i = 0; i < many; i++)
{
if (guess == guessWord[i])
return 0;
if (guess == theWordSecret[i])
{
guessWord[i] == guess;
hits++;
}
}
return hits;
}
void poorStiff(int bodyPart)
{
if (bodyPart == 1)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 2)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| |" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 3)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 4)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|" << endl;
cout << "| / " << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 5)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|" << endl;
cout << "| / |" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 6)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 7)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "| /" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 8)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "| / \." << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 9){
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "| / \." << endl;
cout << "| / " << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 10)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "| / \." << endl;
cout << "| / \." << endl;
cout << "_______________" << endl;
}
}
Did you try debugging? If you step through your code you will immediately find the problem, which is here:
if (theWord == mystery) // the word is the same as mystery
{
cout << theWord << endl;
cout << "\n\n Awesome, you guessed it. \n\n";
break; // problem here
if (attemptsGame < bestScore)
{
bestScore = attemptsGame;
}
// break should be here
}
You're breaking out of your loop before your checking logic. So move your break statement to after the check, because that code never gets executed.
For a start enable your compiler warnings, you'll get many from a quick look at your code.
Change this
guessWord[i] == guess;
to this
guessWord[i] = guess;
At this point
if (wordFill(letter, theWord, mystery) == 0) //fuction call
{
...
cout << "You have entered a letter that isn't in the word, guess again. \n\n";
}
else
{
...
if (theWord == mystery) // the word is the same as mystery
{
cout << theWord << endl;
cout << "\n\n Awesome, you guessed it. \n\n";
break;
...
}
}
Here, when you are entering the first if, then you will enter the second if too, which doesn't make sense. That happens because theWord and mystery are both empty strings!
Also notice that break should be after this part of code:
if (attemptsGame < bestScore)
{
bestScore = attemptsGame;
}
because as it is, this part of code will never be executed.
I suggest taking at this answer (not relevant with your logical error)
System(“pause”); - Why is it wrong?