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
0 个评论
采纳的回答
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
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
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 Center 和 File Exchange 中查找有关 Dates and Time 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!