2

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?

Hopeless Noob
  • 63
  • 1
  • 1
  • 6

2 Answers2

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

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

haccks
  • 104,019
  • 25
  • 176
  • 264
coolbreeze
  • 176
  • 3
0

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;
Pavel Šimerda
  • 5,783
  • 1
  • 31
  • 31
  • this seems to be the inverse operation of what the OP requests. – Jens Gustedt Sep 21 '14 at 08:01
  • @JensGustedt: Not at all, there was just a typo in the name of the function, fixed now. – Pavel Šimerda Sep 21 '14 at 09:08
  • Ah, I see. Unfortunately this is not standard C, but a POSIX extension. – Jens Gustedt Sep 21 '14 at 09:52
  • I wouldn't call POSIX C non-standard, and even less given how useless is ISO C library alone in the modern world with lots network facing and non-blocking code. – Pavel Šimerda Sep 21 '14 at 11:55
  • It is not a question what you call standard or non-standard. These are two different standards, and "standard C" as a term refers to only one of them. (And other than you seem aware off, modern C as of C11 has threads and atomics.) – Jens Gustedt Sep 21 '14 at 11:59
  • Let's not extend this useless discussion any further. We're not here to discuss what you think someone is aware of or not. The answer provides information that wasn't present in any other answer and thus is meant to help anyone for whom it may be useful. And yes, its usefulness depends on the presence of POSIX `strptime()` or a similar function. – Pavel Šimerda Sep 21 '14 at 12:06
  • My second comment was just intended to point you to the fact that this was missing information, here, that normally you would then add to your answer by editing it. – Jens Gustedt Sep 21 '14 at 12:43
  • Next time please try to use a wording that suggests you're encouraging someone to amend the answer, and not just post a random note. – Pavel Šimerda Sep 21 '14 at 12:55