how do I exclude letters as an input ?
26 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2016-11-28
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 个评论
更多回答(1 个)
the cyclist
2016-11-28
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 个评论
Julia Hambright
2018-3-24
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
2018-3-24
Yes, if you use inputdlg you should still assign empty to the variables you test in the while
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!