Hopeless Noob
Hopeless Noob

Reputation: 63

C - Using scanf (or any other function) to get date MM/DD/YYYY in int

I'm writing a C program in class that requires us to input dates as integers in a structure defined as:

typedef struct date{

    int month;
    int day;
    int year;

}Date;

Now that really would not be a problem except it requires that you can only input it as mm/dd/yyyy.

I was thinking if maybe I can input it as a string and just use a loop to seperate the three into other variable strings and convert those to int.

But then I remembered that

printf("Enter Date (MM DD YYYY): ");
scanf("%d %d %d",&...);

is possible. Is there a way to just 'ignore' '/' all together?

Upvotes: 2

Views: 20095

Answers (2)

Pavel Šimerda
Pavel Šimerda

Reputation: 6183

On a system with POSIX strptime() or a similar function, if you first read the string representation into str, you can then use:

struct tm tm;
strptime(str, "%m/%d/%Y", &tm);

It translates to your date as follows:

date.year = tm.tm_year;
date.month = tm.tm_mon;
date.day = tm.tm_mday;

Upvotes: 0

coolbreeze
coolbreeze

Reputation: 176

scanf("%d/%d/%d",&d,&m,&y);

Is probably what you are looking for. This will ignore the / in the input

Upvotes: 9

Related Questions