Info
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
ANSWER: How to check if you wrote string or number
    조회 수: 4 (최근 30일)
  
       이전 댓글 표시
    
Hi there, this might help you out. I made a short code that takes in a number (or string) from a user and returns the number if it sure is a number or 0 if it's a string.
copy and paste in a "script" to try out. Save the script and then test it in comand window.
number = input('Type a number please =  ', 's'); 
% this pice of code can take in both numbers or strings:
number = str2num(number); 
%If the string "number" does not represent a valid number or matrix,
    str2num(number) returns the empty matrix. 
if  isempty(number)
   answer = 0;
else
   answer = daysInMonth(number);
end
disp(answer)
or:
number = input('Type a number please =  ', 's'); 
number = str2num(number); 
if  isempty(number)
 disp('You wrote a text')
else
   fprintf(' You wrote the number %2.0f\n ', number)
end
I know this might be a problem for lots of people which they need an answer to. Lets hope it helps
BenDyAsk
댓글 수: 5
  Walter Roberson
      
      
 2016년 9월 22일
				>> number = input('Type a number please =  ', 's'); 
number = str2num(number); 
Type a number please =  system('ls')
Add-Ons      SupportPackages    projects
Examples    power_V2G_acc.mexmaci64  slprj
You are taking whatever string the user provides and you are executing it.
str2num is coded as very nearly literally
result = eval( [ '[' TheInputString ']' );
so if the user inputs a string that is a valid function call, the function will be executed.
Another example:
>> number = input('Type a number please =  ', 's'); 
  number = str2num(number); 
Type a number please =  pi
>> number
number =
          3.14159265358979
How did number get that numeric value when the user entered something that contains no numbers? Answer: because pi is actually a function, and the function was called.
Is this working "as intended" ??
  Stephen23
      
      
 2016년 9월 22일
				
      편집: Stephen23
      
      
 2016년 9월 22일
  
			Running str2num does not do what the OP thinks, and actually executes the input string. It does not test for string vs. number:
>> str2num('i')
ans =  0 + 1i
>> str2num('exp(3)')
ans =  20.086
>> str2num('mean(+''cheese'')')
ans =  103.50
A much better choice would be str2double.
I am going to close this question because it is misleading, and gives wrong information.
답변 (0개)
이 질문은 마감되었습니다.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!