Error using str = input(prompt,'s')

14 vues (au cours des 30 derniers jours)
Zeynab Mousavikhamene
Zeynab Mousavikhamene le 14 Jan 2020
Modifié(e) : Adam Danz le 14 Jan 2020
I need to ask user whether they have control data or not. if the answer was yes, I need to do other steps.
I tried this coammand:
prompt2='Do you have control? answer Yes/No ';
YesNo = input(prompt2,s);
if YesNo=='Yes'
end
and I got this error:
Undefined function or variable 's'.
What is wrong with this code?

Réponse acceptée

Fangjun Jiang
Fangjun Jiang le 14 Jan 2020
YesNo = input(prompt2,'s')

Plus de réponses (1)

Adam Danz
Adam Danz le 14 Jan 2020
Modifié(e) : Adam Danz le 14 Jan 2020
The problems with using input()
The use of input() can be problematic since the range of inputs the user can intentional or unintentionally enter is wildly unrestrained. For example, in your current code, if the user enters any of the following responses, it will not be detected as "Yes".
  • "YES"
  • "yes"
  • " Yes" (includes leading space)
  • "Yes " (includes trailing space)
The same problem exists for "No" responses. Your current code is only looking for "Yes" matches which means these responses would be considered "No" by default but is this lack of control really what you want?
  • "NO" (does not match "No")
  • "no" (does not match "No")
  • " No" (does not match "No")
  • "No " (does not match "No")
  • "" (empty; by merely pressing enter)
  • "N" (typos; or accidentally pressing enter too early)
  • "lsjdf;ad" (gibberish)
Here are two alternatives that offer much more control over user input.
input() & requiring a valid response
In this method, the user will continually be asked to type Yes or No until his/her response matches one of those options. Furthermore, the response is not case sensitive so the user doesn't have to realize that he/she must use CamelCase.
% Continually prompt user to enter yes or no
% until the response is vaild (case insensitive)
prompt2='Do you have control? answer Yes/No ';
validResponse = false;
while ~validResponse
YesNo = lower(input(prompt2,'s'));
validResponse = ismember(YesNo,{'yes','no'});
end
% Determine which response was entered
if strcmpi(YesNo,'yes')
else
end
questdlg() method
Instead of using input() which allows the user to enter virtually anything, you could highly constrain the inputs by using a question dialog box that only has two options: Yes or No.
% Prompt user to select Yes or No
prompt2= 'Do you have control?';
YesNo = questdlg(prompt2,mfilename,'yes','no','no'); % last input is default selection
% Determine which response was entered
if strcmpi(YesNo,'yes')
else
end

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by