1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
using namespace std;
int main()
{
char word[20]; //holds word
char star[20]; //holds "*"'s for unsolved letters
int count = 0; //Variable for a count
char guess; // char value for entering a guess
int tries; //variable for storing number of tries to be guessed.
int triesLeft; //For displaying the number of guesses left in the puzzle
int x;
cout << "Enter a word to be guessed" << endl;
cin.getline(word, 20);
int puzzLength = strlen(word); //finds length of puzzle, stores INT value to puzzlength
cout << "Enter the number of tries" << endl; // Sets the number of guesses in the puzzle
cin >> tries;
triesLeft = tries; // Sets triesLeft to the correct number of available tries
strcpy_s(star, word); //copy word to the 'star' array
for (count = 0; count < puzzLength; count++) //converts characters to *'s to represent stars
{
if (isalnum(word[count])) star[count] = '*';
else star[count] = word[count];
}
for(x = 0; x <= tries; x++)
{
{
cout << "The word so far: " << star << "." << endl;
cout << "Enter a guess." << endl;
cin >> guess;
triesLeft = tries - x;
}
//For loop for checking if the guess was correct.
for (count = 0; count <= puzzLength; count++)
{
if (guess == word[count])
{
star[count] = guess; //Converts the "star" to the correct answer
cout << "Correct! You have " << triesLeft << " Tries left" << endl;
}
else
cout << "Wrong! you have " << triesLeft << " Tries left" << endl;
}
}
if (strcmp (word, star) != 0)
cout << "You Win!" << endl;
else
cout << "You Lose!" << endl;
cin.get();
return 0;
}
|
That is my code, and for the most part it works. What im having trouble cleaning up, is:
1) Program does not say "You Win" if you guess everything correctly, Ive tried putting if\else statements at the top and bottom of my for loop (which i have there now), ive tried setting a while loop using strcmp, but the program just cant seem to tell whether or not the answer is correct, display the correct message, and exit.
2) When the program checks an answer it checks the entire array (which is good! but..) it gives out "wrong answer" for every letter not guessed correctly, I.E. if the word was "Bunny" and a "B" was entered, output would look like
Correct! you have 4 tries left!
Wrong! you have 4 tries left!
Wrong! you have 4 tries left!
Wrong! you have 4 tries left!
Wrong! you have 4 tries left!
Otherwise, it checks the answer fine, but I havent figured out how to clean up the massive amounts of spam coming out that however.
Any help with fixing those two issues would be greatly appreciated!
(edited to clean up my source code to make it readable)