dark_illusion_909099
dark_illusion_909099

Reputation: 1099

How to go about reading slash (/) from dates using scanf - C

I have currently got it as :

scanf("%d%d%d",&day1,&mon1,&year1);

This works fine when I pass in a date which is to be like :

02-02-2016

However I want it to also be fine if I pass it with slash instead of the dash :

02/02/2016

I have tried this way:

scanf("%d/%d/%d",&day1,&mon1,&year1);

Now this will accept the slash(/) but however does not support dash (-)

How can it accept both ???

How would I go about doing that ? I am new to this language so some sort of advice would be great. Thanks in advance

Upvotes: 1

Views: 3448

Answers (2)

jakeehoffmann
jakeehoffmann

Reputation: 1419

char junk;
scanf("%d%c%d%c%d", &day1, &junk,  &mon1, &junk, &year1);

This would work. You don't have to do anything with the characters you're reading in. If you wanted to disallow anything that isn't - or /, then you could use two variables for those chars, check them to see if they are the values you are allowing, and then printf("Invalid input") or react however you like.

Example, keeps reading input until correct:

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

Dave M.
Dave M.

Reputation: 1537

You can use a format string like: "%d%*[-/]%d%*[-/]%d" to accept only dash or slash between the numbers, but throw away whatever character is there. (This is getting to the outer limits of my scanf knowledge; I don't think I've ever actually used this feature.)

Upvotes: 2

Related Questions