Restrict user string inputs

6 views (last 30 days)
RealA
RealA on 25 Apr 2019
Commented: Adam on 25 Apr 2019
Hey guys, just a quick question, how could I ban all characters inputed by the user execpt 'i' and 'm'.
Thanks
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
while isempty(y)
disp('Blank is an invalid input you are required to enter a number from the options above!')
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
end
while ~strcmp(y,'i') | ~strcmp(y,'m')%Need help in this line of code
disp('Invalid input,please enter the letter ''i'' for an imperial output or ''m'' for a metric output')
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
while isempty(y)
disp('Blank is an invalid input you are required to enter a number from the options above!')
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
end
end
switch y
case 'i'
fahrenheit = (z*9/5)+32
case 'm'
celsius = (z-32)*5/9
end
  1 Comment
Adam
Adam on 25 Apr 2019
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
y = validatestring( y, [ "i", "m" ] );
Depends how stupid you have to treat your users though, by giving them new messages repeating exactly what the first message asked them for if they enter something else!

Sign in to comment.

Answers (1)

M
M on 25 Apr 2019
The problem comes from your conditions:
~strcmp(y,'i') | ~strcmp(y,'m')
This is never true, even if you enter 'i' or 'm'. What you want is to stop when you enter 'i' or 'm', so the criteria to continue the while loop should be the opposite, not 'i' and not 'm':
~strcmp(y,'i') && ~strcmp(y,'m')
This while loop will also stop when you enter 'i' or 'm'

Categories

Find more on Entering Commands in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!