How do I use characters with an if statement?
89 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
0 Commenti
Risposta accettata
Jan
il 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 Commenti
Più risposte (1)
Adam Danz
il 3 Nov 2020
Modificato: Adam Danz
il 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 Commenti
Adam Danz
il 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....
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!