how do I exclude letters as an input ?
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sarah Sadeq
el 28 de Nov. de 2016
Comentada: Walter Roberson
el 24 de Mzo. de 2018
Hello,
I'm working on a project and I'm trying to figure out something and was wondering if someone could help me. I'm asking the user to input positive and non-decimal numbers only. So no strings, no decimals, no negative numbers, no letters, and no blanks.This is my code:
while ( ischar(r) || ischar(c) || isempty(r) || isempty(c))
disp(' ')
disp('You have left an answer blank, or entered a non-numeric value. Please, try again.')
r = input('enter the next row you wish to explore sire: ');
c = input('enter the next column you wish to explore sire: ');
When I run it and input in a letter such as a or b..., my code breaks and an error occurs (the error is Undefined function or variable 'a'.). I tried isletter , but still get the same thing. I would appreciate the help!
0 comentarios
Respuesta aceptada
Walter Roberson
el 28 de Nov. de 2016
r = input('enter the next row you wish to explore sire: ', 's');
c = input('enter the next column you wish to explore sire: ', 's');
while ~isrow(r) || ~isrow(c) || any(r < '0' | r > '9') || any(c < '0' | c > '9')
now whine
and prompt again
end
r = str2double(r);
c = str2double(c);
0 comentarios
Más respuestas (1)
the cyclist
el 28 de Nov. de 2016
The issue is that MATLAB evaluates the input. If you just enter a letter (without quotes), then MATLAB evaluates it, can gets an error. This is mentioned in the Description section of the documentation for the input function.
There is a syntax that will read the input as a string, without evaluating it. See the code below. I also had to edit your conditions, to parse out non-empty numeric entries. It's a bit kludgy, but it works. It would not surprise me if there is a more parsimonious way to do this.
r = '';
c = '';
while ( not(isnumeric(str2num(r))) || not(isnumeric(str2num(c))) || isempty(str2num(r)) || isempty(str2num(c)))
disp(' ')
disp('You have left an answer blank, or entered a non-numeric value. Please, try again.')
r = input('enter the next row you wish to explore sire: ','s');
c = input('enter the next column you wish to explore sire: ','s');
end
2 comentarios
Julia Hambright
el 24 de Mzo. de 2018
I am having the issue of matlab not being able to handle a letter input without quotes and I would like to use this code. I was wondering, however, if I am using inputdlg(), then would i define r = ' '; before using inputdlg()? and how will it put a letter into a string if it is being redefined after the user inputs a value Thanks!
Walter Roberson
el 24 de Mzo. de 2018
Yes, if you use inputdlg you should still assign empty to the variables you test in the while
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!