Effacer les filtres
Effacer les filtres

strings, while loop help

2 vues (au cours des 30 derniers jours)
Chris
Chris le 5 Déc 2011
clear; clc;
fid = fopen('hangman.txt','r');
if fid < 0, error('Cannot open file');
end
data = textscan(fid,'%s');
data = data{1};
fclose(fid);
index = ceil(rand * numel(data));
word = data{index};
masked = word;
masked(~isspace(masked)) = '*';
complete = 0;
while complete == 0
clc; fprintf('Word : %s\n',masked);
letter = (input('Guess a letter : ','s'));
stat = findstr(word,letter);
if ~isempty(stat)
masked(stat) = letter;
end
if isempty(findstr(masked,'*'))
complete = 1;
end
end
clc; fprintf('Word : %s\n',masked);
My letters are still case sensitive, not sure why. And I'm not sure how I could break the while loop so it stops after six incorrect guesses.
  1 commentaire
Walter Roberson
Walter Roberson le 5 Déc 2011
http://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-with-markup
Please remember that if you write your questions in a format that is difficult for the volunteers to understand, they might choose to skip the question rather than puzzling it out. It is thus to your advantage to spend time learning how to format code.

Connectez-vous pour commenter.

Réponse acceptée

Sven
Sven le 5 Déc 2011
Chris, try this:
word = 'MyMatlab';
masked = repmat('*', size(word));
wrongGuesses = 0;
wordGuessed = false;
while wrongGuesses < 6
clc; fprintf('Word : %s\n',masked);
% Note we're forcing everything to lower case
letter = lower(input('Guess a letter : ','s'));
wordMask = lower(word)==letter;
if any(wordMask)
masked(wordMask) = letter;
else
wrongGuesses = wrongGuesses+1;
end
if ~any(masked=='*')
wordGuessed = true;
break; % This exits out of the while loop
end
end
clc; fprintf('Word : %s\n',masked);
You'll see above that we can use lower to remove case-sensitivity. Also note that I'm using a straight letter comparison via the == operator. This is because findstr is not recommended (it will be removed in a future version of MATLAB), but you could just as easily use strfind (I know... confusing.)
Also note the two ways to exit the loop. One coming from too many wrong guesses, another coming from the break statement if all asterixs have been replaced. You'll be able to tell which exit happened by checking the wordGuessed boolean.

Plus de réponses (1)

Sean de Wolski
Sean de Wolski le 5 Déc 2011
you can use lower and upper to force strings to your choice of capitalization.
doc lower
doc upper

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by