You could try this:
scanf(" %3d%1[/-]%3d%1[/-]%5d", ...);
Because those fields widths only specify the maximum widths, but not the minimum widths, they cannot be used to distinguish input with narrow fields. Therefore, if you want to restrict the input formats to dd/mm/yyyy
or dd-mm-yyyy
strictly, you need do more syntax checks after scanf()
returns successfully.
Here is a test program:
#include <stdio.h>
int
main(void)
{
int yy, mm, dd;
char del1[2], del2[2];
const char *dates[] = {
/* well formed */
"28-03-2014",
"-28-03-2014",
"28--03-2014",
"28-03--2014",
"28/03/2014",
"-28/03/2014",
"28/-03/2014",
"28/03/-2014",
/* ill formed */
"28-3-2014",
"8-03-2014",
"28-03-14",
"28-03/2014",
"28/03-2014",
"28 03 2014",
NULL,
};
for (size_t i = 0; dates[i]; i++) {
int ret = sscanf(dates[i], " %3d%1[/-]%3d%1[/-]%5d", &dd, del1, &mm, del2, &yy);
if (ret != 5 || del1[0] != del2[0]) {
fprintf(stderr, "%s : syntax error\n", dates[i]);
continue;
}
printf("del = %c, yy = %d, mm = %d, dd = %d\n", del1[0], yy, mm, dd);
}
return 0;
}