How can I make a function restart if a string input by a user is not terminated properly instead of it breaking the code with an error?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Andrew Williams
am 15 Apr. 2017
Kommentiert: Andrew Williams
am 15 Apr. 2017
I am new to this software and I understand that this is an elementary question. An example of what I'm trying to figure out is this:
function [n]=name
n=input('Please enter your name')
If the user enters 'Name and leaves it like that, the code will break. How do I make it restart the function to take the input again?
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 15 Apr. 2017
You want the user to enter a name, not some code that's evaluated to generate a name. In that case, call the input function with the 's' flag as shown in the second section of the Description and the second Example on that function's documentation page.
Weitere Antworten (1)
the cyclist
am 15 Apr. 2017
One way would be to write the function with a while loop, something like this
function [n] = name
n = '';
while <some condition that you specify for _n_ goes here>
n=input('Please enter your name')
end
end
The while loop will keep repeating until the user puts something that meets your condition.
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!