0

I'm new to C, currently studying it on CS50 course on edx.org (this task is NOT from CS50 course).

I wrote the program which asks the user for a date of birth, and then calculates a current age depending on system date.

Now I'm getting values from user this way (GetInt() and GetString() are functions from cs50.h header and library).

// Ask user for his name, and date of birth

printf("Enter your name: ");
char* name = GetString();

printf("Enter your day of birth: ");
int birth_day = GetInt();

printf("Enter your month of birth: ");
int birth_month = GetInt();

printf("Enter your year of birth: ");
int birth_year = GetInt();

But I don't want to ask user 3 times to get a date that he can enter as one line - 18.06.1985 for example.

So the question is - how to get input from user in format DD.MM.YYYY, then store it in the array of integers, as [0, 1, 2], so I would be able to access these values separately later on?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Nikita K.
  • 23
  • 1
  • 5

2 Answers2

3

You can do the following:

int array[3];
scanf("%d.%d.%d", &array[0], &array[1], &array[2]);

On an input of 18.06.1990, array[0] will contain 18, array[1] will contain 6 and array[2] will have 1990.

KKishore
  • 452
  • 5
  • 12
  • Thank you, this is also right, but if this works, i even don't need an array! – Nikita K. Feb 06 '16 at 11:38
  • Don't forget to check that `scanf()` returned `3` before using the values. (@NikitaK. — you're right that you don't have to use an array; you can use any three distinct variables.) Life gets more interesting if you want to be flexible about the date format, so you want to allow DD/MM/YYYY and DD MM YYYY as well as DD.MM.YYYY format (and still more interesting if you want to allow DDMMYYYY — let alone YYYY-MM-DD too, or MM/DD/YYYY, or …) Dates are endlessly entertaining (for a very low grade of entertainment value). – Jonathan Leffler Jul 31 '16 at 15:24
1

Create a struct to get that:

typedef struct {
    int day;
    int month;
    int year;
} birthDay;

When you're going to ask the user, you can do:

int day, month, year;
printf("Type your birthday (day month year): ");
scanf("%d %d %d", &day, &month, &year);

Now, you can set your struct properly.

birthday bday;
bday.day = day;
bday.month = month;
bday.year = year;
Paulo
  • 1,458
  • 2
  • 12
  • 26
  • Thank you, this helps! I just didn't know how to use scanf() propertly – Nikita K. Feb 06 '16 at 11:37
  • 2
    Note that you should check the return value of `scanf`: if the user gave proper input, 3 numbers optionally separated by white space, the return value will be 3, otherwise, some of the variables `day`, `month`, year` may not have be set at all. – chqrlie Feb 06 '16 at 11:40