Restrict user string inputs
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
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!
Réponses (1)
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'
0 commentaires
Voir également
Catégories
En savoir plus sur Entering Commands 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!