How to use if statement to compare strings
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
So I have an input statement to enter a gender that asks the user to input m for male and f for female. I only want the user to input either m or f. I have:
if genderInput ~= m || genderInput ~= f
genderInput = input('Please enter a valid input.\n');
end
but it doesn't work. Why doesn't it work?
1 Kommentar
Dennis
am 5 Nov. 2018
it is not clear if m and f are the strings you want to compare with or if they are variables holding the string.
For comparing strings in the first place you might want to use
strcmp or strcmpi
Antworten (2)
Bruno Luong
am 5 Nov. 2018
Bearbeitet: Bruno Luong
am 5 Nov. 2018
if isempty(genderInput) || (lower(genderInput(1)) ~= 'm' || lower(genderInput(1)) ~= 'f')
genderInput = input('Please enter a valid input.\n');
end
1 Kommentar
Bruno Luong
am 5 Nov. 2018
Bearbeitet: Bruno Luong
am 5 Nov. 2018
The code can accept both format short ('m' 'f'} or long {'male' 'female'}, lower-case as well as upper-case based on the first character.
Stephen23
am 5 Nov. 2018
gI = '';
while ~ismember(gI,{'m','f'})
gI = input('Enter gender: ','s');
end
0 Kommentare
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!