Restrict user string inputs

3 visualizzazioni (ultimi 30 giorni)
RealA
RealA il 25 Apr 2019
Commentato: Adam il 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 Commento
Adam
Adam il 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!

Accedi per commentare.

Risposte (1)

M
M il 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'

Categorie

Scopri di più su Loops and Conditional Statements 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!

Translated by