Nikita K. Nikita K. - 1 year ago 45
C Question

How to get an input from user as an integers array in C?

I'm new to C, currently studying it on CS50 course on (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 (

are functions from
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?

Answer Source

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; = day;
bday.month = month;
bday.year = year;