Restrict user string inputs

5 vues (au cours des 30 derniers jours)
RealA
RealA le 25 Avr 2019
Commenté : Adam le 25 Avr 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 commentaire
Adam
Adam le 25 Avr 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!

Connectez-vous pour commenter.

Réponses (1)

M
M le 25 Avr 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'

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by