Hey,have been having a problem with this code,dont no what to do here,trying to find the letter in the secret word in hangman.when the user inputs their choice how do i compare it with the secret word.was using a for loop but not sure

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";
          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';
          while (lives>0 && wordguessed!=word_to_guess)
               cout<<"You have "<<lives<<" guesses left"<<endl<<endl;
               cout<<"Please enter your guess"<<endl<<endl;
               lives = lives -1;
               lettersguessed = lettersguessed + guess;   
               for(int h =0;h<word_to_guess.size();h++)
                       word_to_guess[h]== guess;

Didn't you ask this in your other "newbie" thread? You have to compare to the word in your original word array, then place the character in the proper location in your "word_to_guess" array. If you assume the secret word is "freedom" and the user enters 'r' your loop would loop through the known "freedom", then when a character matches, it assigns the character to the correct element in "word_to_guess" so that you get something like "XrXXXXX".

A for loop is probably the better choice. A while loop would work, but it would likely take a little more effort. It really depends on what you already know from/about the situation.

Edited 6 Years Ago by Fbody: n/a

Thank you it works now,it just doesnt change the first 'X' even if the letter is correct???

You're probably starting at 1 instead of 0. Don't forget, C++ array element indexes are 0 to (SIZE-1)

This article has been dead for over six months. Start a new discussion instead.