hj13
hj13

Reputation: 13

How to use scanf to reject input that mixes delimiters in date (ex. 15/01-2015)?

I need to check if the user input is using the correct delimiters. However the code I have right now would still allow for example "15-10/1999", which it shouldn't. I'm not quite sure how exactly to change the while condition to disallow this though.

char delim1, delim2;
do { 
    printf("Please enter date (dd-mm-yy or dd/mm/yy):");   
    scanf("%d%c%d%c%d", &day1, &delim1,  &mon1, &delim2, &year1);
} while (delim1 != '-' && delim1 != '/' && delim2 != '-' && delim2 != '/');

Upvotes: 1

Views: 28

Answers (3)

Chris Dodd
Chris Dodd

Reputation: 126253

Easiest way is to match the delimeter in the fmt string and CHECK THE RETURN VALUE OF scanf!!!!

printf("Please enter date (dd-mm-yy or dd/mm/yy):");
while ((cnt == scanf("%u/%u/%u", &day, &mon1, &year1)) != 3) {
    if (cnt == 1 && scanf("-%u-%u", &mon1, &year1) == 2) break;
    if (scanf("%*[^\n]") == EOF) {   // discard the rest of the line
        exit(1);  // alternately clearerr(stdin); if you want to try
        // again despite the error or eof
    }
    printf("Invalid input, please enter date (dd-mm-yy or dd/mm/yy):");
}

Upvotes: 1

learning2learn
learning2learn

Reputation: 411

Untested:

char delim1, delim2;
do { 
    printf("Please enter date (dd-mm-yy or dd/mm/yy):");   
    scanf("%d%c%d%c%d", &day1, &delim1,  &mon1, &delim2, &year1);
} while (!(delim1 == '-' && delim2 == '-') || !(delim2 == '&' && delim2 == '&'));

Upvotes: 0

Ctx
Ctx

Reputation: 18420

You can use:

while (delim1 != delim2 || (delim1 != '-' && delim1 != '/'));

This ensures that the delimiters are equal after the while condition is satisfied and that it is either '-' or '/'.

Upvotes: 1

Related Questions