How do I use characters with an if statement?

48 vues (au cours des 30 derniers jours)
John Jamieson
John Jamieson le 3 Nov 2020
Commenté : Adam Danz le 1 Sep 2021
My code looks like this
Prompt='Please press any key to roll the dice, press Q or q to quit program: ';
str=input(Prompt, 's');
if str == q||Q
fprintf('program terminated')
end
end
Essentially what I want to do is if the user inputs Q, the fprintf statement is true. However, I'm unsure of how to do this, as it only see's q as an unrecognized value

Réponse acceptée

Jan
Jan le 3 Nov 2020
Prompt = 'Please press any key to roll the dice, press Q or q to quit program: ';
str = input(Prompt, 's');
if strncmpi(str, 'q', 1)
fprintf('program terminated')
end
strncmpi compares the given number of characters ignoring the case. This is nicer than:
if ~isempty(str) && str(1) == 'q' || str(1) == 'Q'
or
if ~isempty(str) && lower(str(1)) == 'q'
  2 commentaires
Ishana Alviar
Ishana Alviar le 1 Sep 2021
why does it need to have 's' ?
Adam Danz
Adam Danz le 1 Sep 2021
See documentation,

Connectez-vous pour commenter.

Plus de réponses (1)

Adam Danz
Adam Danz le 3 Nov 2020
Modifié(e) : Adam Danz le 3 Nov 2020
If you want to consider case (assuming str, q, and Q are all strings or character arrays)
if any(strcmp(str, {q,Q})) % [q,Q] for string arrays
or
if ismember(str, {q,Q}) % [q,Q] for string arrays
If you want to ignore case
if any(strcmpi(str, {q,Q})) % [q,Q] for string arrays
or
if ismember(lower(str), lower({q,Q})) % [q,Q] for string arrays
  2 commentaires
Rik
Rik le 3 Nov 2020
I suspect q and Q were meant as literal characters, not variables.
Adam Danz
Adam Danz le 3 Nov 2020
@John Jamieson In that case (see Rik's comment above), {q,Q} would be {'q','Q'} or ["q","Q"] for strings.
Also, just a public service announcement, when using input() you should include input validation. For example,
if you're expecting a single character,
assert(numel(str)==1, 'Input must be 1 character.')
if you're expecting a word with no spaces,
assert(any(isspace(str)), 'Input must not contain spaces.')
if you're expecting only letters and no numbers,
assert(all(isletter(str)),'Input must only be letters')
etc....

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by