reject input if it is a string

30 visualizaciones (últimos 30 días)
Joe Smart
Joe Smart el 6 de Oct. de 2017
Editada: Cedric el 6 de Oct. de 2017
When using the input function in this way:
m = input('please enter the mass: ')
How can I have the script reject the answer and try again if the input is a string?
I have tried
m = input('Please enter the mass: ')
tf = isstring(m);
if tf == 1
disp('Your input was a string, please try again')
else
weight = m * 9.81;
end
This works usually, but on some inputs, such as 'word' it returns an error:
Error using input
Undefined function or variable 'word'.
Error in itertow (line 6)
w1 = input('Please estimate a value for take off weight in kg: ');
If I enter 'string' as my input it behaves as expected.
Any explanation or help would be greatly appreciated, thanks.

Respuestas (3)

Cedric
Cedric el 6 de Oct. de 2017
Editada: Cedric el 6 de Oct. de 2017
Here is what I think you don't understand: INPUT evaluates what the user types unless called with a second 's' argument (in which case it outputs a char array):
>> in = input( ':', 's' )
:Hello
in =
'Hello'
>> class(in)
ans =
'char'
Without the 's', the input from user is evaluated and if it is a valid MATLAB expression it's output is stored in the output parameter (if not, an exception/error is thrown). When you pass string, it is a valid expression actually, as string is a MATLAB class and this calls its constructor. Doing this, you instantiate the class and create a string object:
>> in = input( ':' ) ;
:string
>> class(in)
ans =
'string'
When you pass word, it fails as word is not a valid MATLAB command/function/expression.
If you want to manage the failure to enter a valid number, you can capture the error if any, test the input, etc, or save the expression as a string and try to convert to numeric afterwards.
I advise you the latter approach (so you don't have to deal with a TRY/CATCH statement). Here is a hint:
>> str2double( 'word' )
ans =
NaN
so you could ask for a mass while the outcome of what you read as a string converted to double (numeric) is not NaN.
  2 comentarios
Image Analyst
Image Analyst el 6 de Oct. de 2017
Yep, that's what my code does. Tries to convert, and if it fails, assigns the default and tells the user.
Cedric
Cedric el 6 de Oct. de 2017
Editada: Cedric el 6 de Oct. de 2017
We all posted 3 hours ago, probably in parallel.

Iniciar sesión para comentar.


dpb
dpb el 6 de Oct. de 2017
Editada: dpb el 6 de Oct. de 2017
From the documentation we find that input "requests user input , ... waits for input from the keyboard, evaluates any expressions in the input, and then returns the result."
The damage is done before you have a chance at it owing to the evaluation step. Instead, turn it around and request the input be returned as the string the user typed, then evaluate whether it is a valid number...
m = input('Please enter the mass: ','s'); % return input as string, shortcut eval
m = str2double(m); % try to convert to number
if ~isfinite(m)
% error branch here...
You'll want to either put the request in try...catch block to retry or add a while loop or other way to repeat the input until do get a valid response...

Image Analyst
Image Analyst el 6 de Oct. de 2017
Look at these two snippets. Adapt as needed:
% Ask user for one integer number.
defaultValue = 45;
titleBar = 'Enter an integer value';
userPrompt = 'Enter the integer';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
integerValue = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(integerValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
integerValue = defaultValue;
message = sprintf('I said it had to be an integer.\nTry replacing the user.\nI will use %d and continue.', integerValue);
uiwait(warndlg(message));
end
%----------------------------------------------------------------
% Ask user for two floating point numbers.
defaultValue = {'45.67', '78.91'};
titleBar = 'Enter a value';
userPrompt = {'Enter floating point number 1 : ', 'Enter floating point number 2: '};
caUserInput = inputdlg(userPrompt, titleBar, 1, defaultValue);
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue1 = str2double(caUserInput{1})
usersValue2 = str2double(caUserInput{2})
% Check usersValue1 for validity.
if isnan(usersValue1)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
% Convert the default from a string and stick that into usersValue1.
usersValue1 = str2double(defaultValue{1});
message = sprintf('I said it had to be a number.\nTry replacing the user.\nI will use %.2f and continue.', usersValue1);
uiwait(warndlg(message));
end
% Do the same for usersValue2
% Check usersValue2 for validity.
if isnan(usersValue2)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
% Convert the default from a string and stick that into usersValue2.
usersValue2 = str2double(defaultValue{2});
message = sprintf('I said it had to be a number.\nTry replacing the user.\nI will use %.2f and continue.', usersValue2);
uiwait(warndlg(message));
end

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by