Can I use the input function to ask for both a number or a string?
20 次查看(过去 30 天)
显示 更早的评论
I know that the function interprets no conditions as a number and ,'s' as a string input. Is there any way I could have the user choose to input either a string or a number using the same line of code?
0 个评论
回答(3 个)
Geoff Hayes
2018-2-11
Gavin - you could perhaps use str2double to determine if the input is a string or number. Perhaps something like
str = input('please enter a string or number: ', 's');
if ~isnan(str2double(str))
fprintf('user entered a number\n');
else
fprintf('user entered a string\n');
end
If the conversion from the string to a double is NaN, then the user entered a string (or something that cannot be converted to a number). Else the user entered a number.
0 个评论
Jan
2018-2-11
You can use input to obtain a string in every case and interpret as string or number as you like it. Note that if the user types in "9", you can interpret it is as number 9 or string '9' also. So how do you want to decide, what it is?
Please explain the problem, you want to solve. Using the wooden input in the command window is worse than a smart GUI. Maybe it is better to create a real GUI directly.
0 个评论
Walter Roberson
2018-2-11
Yes. If you use input() without the 's' option, then the user can choose to input a string by enclosing it in quotation marks. Whatever the user enters will be executed, so if the result of the execution is a character vector then that is what will be returned.
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!