Storing outputs in a vector
    3 views (last 30 days)
  
       Show older comments
    
Hi! I am trying to code a hangman game and I am struggling to turn one of my variables into a vector. I attached the code below but for context I am trying to turn G (input of a letter) into a vector so that every time I guess a letter it saves it into a vector so that I can use an fprintf statement to display every guess to the user.
A=0;%The number of attempts
guess;
listword
while A<6 %setting a while loop for the not exceeding the amount of wrong guesses the user has
    fprintf('\nThis is attempt %d you get up to 6 incorrect guesses',A)
    G=input('\nGuess a letter: ','s')
    N=0;
    for z=1:L; %creating a for loop to inspect the length of the word to determine if the letter is present
        if G==guess(z); %if it is then the letter is displayed
            listword(z)=G
            N=N+1;
        else
            N==0;
        end
    end
end
0 Comments
Answers (1)
  Geoff Hayes
      
      
 on 15 Nov 2017
        Amanda - if you just want an array of all of the user's current character guesses, then just append your G to this array once the guess has been made. For example, you could create an array as
 listOfGuesses = '';
 while A < 6
     fprintf('\nThis is attempt %d you get up to 6 incorrect guesses',A)
     newGuess = input('\nGuess a letter: ','s')
     listOfGuesses = [listOfGuesses newGuess];
     % etc.
 end
So we have a list of guesses upon which we append the newest guess (note that you may want a check to see if this guess has been made already, or you may want to sort this list).
It isn't clear what the guess variable is to be used for. Presumably it is a string of L characters that the user is trying to guess (since Hangman)? Rather than iterating over each element of guess, you could use the find function to check to see which characters match the guess. For example,
 message = 'This is the message that you need to guess';
 yourGuess = blanks(length(message));
 yourGuess(:) = '*';
 listOfGuessedLetters = '';
 A = 0;
 while A < 6
     A = A + 1;
     fprintf('\nThis is attempt %d you get up to 6 incorrect guesses',A)
     letter = input('\nGuess a letter: ','s')
     listOfGuessedLetters = [listOfGuessedLetters letter];
     [indices] = find(message == letter);
     if ~isempty(indices)
         yourGuess(indices) = letter;
     end
 end
You may also want to decide whether you should ignore (upper or lower) case.
0 Comments
See Also
Categories
				Find more on Entering Commands in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
