Store a variable from prompt user input

조회 수: 4 (최근 30일)
Kundera
Kundera 2017년 6월 8일
댓글: Stephen23 2017년 6월 8일
Hi, I have this function which display a request in the prompt and asks user to input a number. The function then repeats until user inputs a valid number.
function num = inputNumber(prompt)
while true
num = str2double(input('Write your age :', 's'));
if ~isnan(num)
break;
end
end
I want then to store the input in the variable num but it is not happening. Why? How can I solve it? Thanks

채택된 답변

Stephen23
Stephen23 2017년 6월 8일
편집: Stephen23 2017년 6월 8일
I changed it so that there is a limit to how many attempts can be made, and also that the output is always defined:
function out = inputNumber(prompt)
out = NaN;
tot = 3; % how many attempts to make
while isnan(out) && tot>0
out = str2double(input('Write your age :', 's'));
tot = tot-1;
end
end
and tested:
>> num = inputNumber()
Write your age: 64
num = 64
  댓글 수: 4
Kundera
Kundera 2017년 6월 8일
Thanks a lot @Stephen. I am a beginner, so much to learn :-)
Stephen23
Stephen23 2017년 6월 8일
@Kundera: my pleasure. Please do read the links that I gave.
You should accept the answer that best resolves your original question. Accepting answers is an easy way for you to show your thanks for us volunteers.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by