how do I exclude letters as an input ?
이전 댓글 표시
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!
채택된 답변
추가 답변 (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
카테고리
도움말 센터 및 File Exchange에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!