Unrecognized function or variable
6 次查看(过去 30 天)
显示 更早的评论
I am trying to make a centigrade to fahrenheit converter with build in check for strings and I want the program to be reset itself when a non numerical value is given as input. This is what I got so far:
val=input('Centigrade: ');
tf=isstring(val);
if tf==0
Fahrenheit=val.*9/5+32
else tf==1
disp('Your input was a string, please try again')
end
The code works for numerical values, but when I enter 'w' for example it also generates a value in fahrenheit. When I leave out the '' (just entering w) it gives me the following error:
Error using input
Unrecognized function or variable 'w'.
Error in Untitled6 (line 5)
val=input('Centigrade: ');
Anyone who can tell me what I should do and why the code isn't working properly?
Thanks in advance!
0 个评论
采纳的回答
Walter Roberson
2020-2-12
'w' is not a string, it is a character. isstring() tests specifically for string() objects.
When you use input() without the 's' option then everything that is entered is executed with eval(). If the input includes text that does not happen to match a variable or function name then when the eval() happens you will get the error message that you saw.
I would recommend that you stop trying to test only for strings, because when you use input() the user can enter any code to return any data type.
What I recommend is that if you use input() that you use the 's' option. When you do that, the user input is not executed and is returned as a character vector (not a string object). If the user entered 1.23 at the input prompt, then '1.23' character vector would be returned, not the number 1.23. Then with the character vector in hand, use str2double. That function has the property that if the input does not represent exactly one number, then the function returns nan. Only regular number-building characters are permitted. Entering w or 1,2 would get you a nan result. And if the user did enter a single number then you get the numeric value rather than nan.
0 个评论
另请参阅
类别
在 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!