-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafeinput.m
More file actions
35 lines (30 loc) · 855 Bytes
/
safeinput.m
File metadata and controls
35 lines (30 loc) · 855 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function x = safeinput(prompt, validator, val_msg)
% input that reprompts instead of errors if you make a typo.
% also reprompts if input does't pass validator function, if used.
% if input does not pass validation, issues a warning including the
% optional val_msg, which should be formatted as a sentence.
if nargin < 2 || isempty(validator)
validator = @(~) true;
end
if nargin < 3
val_msg = '';
end
while true
raw_input = input(prompt, 's');
try
% use eval to get around weird reprompting behavior of `input`
if isempty(raw_input)
x = [];
else
x = eval(raw_input);
end
if validator(x)
return;
else
warning(['Invalid input - try again. ', val_msg]);
end
catch
warning('Invalid syntax - try again.');
end
end
end