How do I set the number of digits to be entered for input and display an error message if this is not met?

3 次查看(过去 30 天)
I want the the user to enter a date and year. How do I make it so that four digits must be entered for the year, and that two digits must be entered for the date (leading zeros are okay)? I know that I can use an if statement with the error function, but is there a function to set the number of characters for input that I can use with the if statement?
Thanks

采纳的回答

Geoff Hayes
Geoff Hayes 2014-10-15
You could use length to check to see if the user has entered six characters, and raise an error if this is not true
dateString = input('Enter a date and year (YYYYMM): ','s');
if length(dateString)~=6
error('invalid date string (not enough characters)');
end
To check to see if only numeric characters have been entered, then use regexp as
dateString = input('Enter a date and year (YYYYMM): ','s');
if length(dateString)~=6
error('invalid date string (not enough characters)');
elseif ~isempty(regexp(dateString,'\D'))
error('invalid date string (non-numeric characters)');
end
  5 个评论
Geoff Hayes
Geoff Hayes 2014-10-15
What is your input statement? Because if you do something like
result = input('please enter a number: ')
then result is of type double and so you convert it to a string, as you have shown in the above code. But if you add the 's' to your input
result = input('please enter a number ', 's')
then result is of type char and so there is no need to convert it to a string. So if the user types in 0003, then
result == '0003'
with no loss in leading zeros.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by