how do I exclude letters as an input ?
10 ビュー (過去 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
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!