How do I use characters with an if statement?

87 次查看(过去 30 天)
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

采纳的回答

Jan
Jan 2020-11-3
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'

更多回答(1 个)

Adam Danz
Adam Danz 2020-11-3
编辑:Adam Danz 2020-11-3
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 个评论
Rik
Rik 2020-11-3
I suspect q and Q were meant as literal characters, not variables.
Adam Danz
Adam Danz 2020-11-3
@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....

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by