Check input is a string or Char if so reprompt

I am struggling to fidn a way to check a input if its any type of string or char and if so reprompt the user.
Code is below:
a = input("Please enter a number: "); %Takes user input for number that is to be converted
while isempty(a)
disp('Invalid input please enter a number!')
a = input("Please enter a number: ");
end
convtype = input("Please enter the conversion type: "); %Takes user input for the cnversion type that they want
while isempty(convtype)|| convtype < 1 || convtype > 14
disp('Invalid conversion type selection please make a selection between 1 and 14!')
convtype = input("Please enter the conversion type: ");
end

댓글 수: 2

If you specify the 's' option then INPUT will always return a character vector:
txt = input(prompt,'s')
Methat
Methat 2024년 5월 6일
so it will return that value as a charecter lets say I need to use that value later for a calculation I would need to convert it back to a numerical input. Also if I were to do this would I use ischar() to check if its charecter to ten reprompt the user to re-enter their value?

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

답변 (1개)

Walter Roberson
Walter Roberson 2024년 5월 6일

0 개 추천

a = input("Please enter a number: "); %Takes user input for number that is to be converted
while ~isnumeric(a) || numel(a) ~= 1
disp('Invalid input please enter a number!')
a = input("Please enter a number: ");
end
convtype = input("Please enter the conversion type, integer 1 to 14: "); %Takes user input for the cnversion type that they want
while ~isnumeric(convtype) || numel(convtype) ~= 1 || convtype ~= floor(convtype) || convtype < 1 || convtype > 14
disp('Invalid conversion type selection please make a selection between 1 and 14!')
convtype = input("Please enter the conversion type as an integer 1 to 14: ");
end

댓글 수: 3

Methat
Methat 2024년 5월 6일
Hi I was just wondering what does the ~ do specifically as I have never seen the use of ~ in MATLAB. Sorry for this question if it is obvious I am very new to MATLAB.
Methat
Methat 2024년 5월 6일
Oh I see thanks for the help I will try using ~ in my current iteration on the code thanks for linking those explinations.

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

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

태그

질문:

2024년 5월 5일

댓글:

2024년 5월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by