-
Find letter
Having a problem with my code for an assignment i'm doing,it's hangman.When I get the input from the user i want to check to see if it is in the secret word.I think i'm on the right track.any suggestions????
Code:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
int lives;
int num;
int strsize ;
string word_to_guess;
string wordguessed;
string words [10] = {"Dell","School","Phone","Water","Book","Computer","Window","Matches","Television","Bed"};
string lettersguessed;
string guess;
cout<<"\n\t\t *********** H A N G M A N ***********\n\n";
cout<<"\n\t\t Welcome to To the game of Hangman \n\n";
cout<<"\n\t\t Guess the letters of the random word \n\n";
srand((unsigned)time(NULL));
num = rand() % 9 + 0;
word_to_guess = words[num];
strsize = word_to_guess.size();
lives = word_to_guess.size();
lives = lives + 2;
cout<<"Guess the secret word it has "<<strsize
<<" letters and you guess one letter at a time "<<endl<<endl;
wordguessed = word_to_guess;
for(int i = 0; i<word_to_guess.size();i++)
{
word_to_guess[i] = 'X';
}
cout<<word_to_guess<<endl<<endl;
while (lives>0 && wordguessed!=word_to_guess)
{
cout<<"You have "<<lives<<" guesses left"<<endl<<endl;
cout<<"Please enter your guess"<<endl<<endl;
cin>>guess;
lives = lives -1;
lettersguessed = lettersguessed + guess;
for (int i=0; i=word_to_guess.size();i++)
{
word_to_guess[i] = guess;
}
cout<<word_to_guess;
cout<<"Your letters "<<lettersguessed<<endl<<endl;
-
Well, there's different methods of doing this, a simple one may be something like;
Code:
int main()
{
std::string secret_word="pizza";
char l;
std::cout<<"enter a letter: ";
std::cin>>l;
std::cin.ignore();
for (int i=0; i<secret_word.length();i++)
{
if (secret_word[i] == l){
std::cout<<"found letter";
}
}
std::cin.get();
return 0;
}
-
what error messages are you getting? just glancing through, i would think that guess should be a char rather than a string.
with guess as string, i'm kind of surprized that the compiler will accept the assignment:
Code:
word_to_guess[i] = guess;
i'm also kind of confused as to why you re-assign word_to_guess to be XXXX rather than wordguessed, which would seem to be the part of the word that's actually been guessed (?).
seems to me that, yes, there's part of the solution here, but only part of it, and that part also needs a little work, too.
-
You'd also want to remove or replace those letter(s) found with the string so they're not Id'd and compared again. The method I used once was that if a letter was found, it'd be replaced by a '*' and once the entire string was *****, the game was won. Quite simple and requires little code -