How to use if statement to compare strings

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

Dennis
Dennis 2018년 11월 5일
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

댓글을 달려면 로그인하십시오.

답변 (2개)

Bruno Luong
Bruno Luong 2018년 11월 5일
편집: Bruno Luong 2018년 11월 5일

0 개 추천

if isempty(genderInput) || (lower(genderInput(1)) ~= 'm' || lower(genderInput(1)) ~= 'f')
genderInput = input('Please enter a valid input.\n');
end

댓글 수: 1

Bruno Luong
Bruno Luong 2018년 11월 5일
편집: Bruno Luong 2018년 11월 5일
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
Stephen23 2018년 11월 5일

0 개 추천

gI = '';
while ~ismember(gI,{'m','f'})
gI = input('Enter gender: ','s');
end

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

릴리스

R2018a

질문:

PJ
2018년 11월 5일

편집:

2018년 11월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by