Can I use the input function to ask for both a number or a string?
18 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (3)
Geoff Hayes
am 11 Feb. 2018
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 Kommentare
Jan
am 11 Feb. 2018
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 Kommentare
Walter Roberson
am 11 Feb. 2018
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 Kommentare
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!