Home > OS >  C struct array input and output
C struct array input and output

Time:01-29

I am trying to build a program which takes user input of employee details and prints it. I have separate functions for both of them.

Structure is as follows:

struct employee
{
    int empId;
    char name[20];
    char empType[10];
    int dd, mm, yyyy;
};

struct employee input()
{
    struct employee e;

    printf("Enter Employee ID: \n");
    scanf("%d", &e.empId);

    printf("Enter Employee name: \n");
    scanf("%s", &e.name);

    printf("Enter employee type: \n");
    scanf("%s", &e.empType);

    printf("Enter joining date: \n");
    scanf("%d/%d/%d", &e.dd, &e.mm, &e.yyyy);
}

void display(struct employee emp[], int n)
{
    printf("Employee ID \t Name \t Employee Type \t Joining date\n");
    int i;
    for (i = 0; i < n; i  )
    {
         printf("%d %s %s %d/%d/%d", emp[i].empId, emp[i].name, emp[i].empType, emp[i].dd, emp[i].mm, emp[i].yyyy);
    }
}

int main()
{
    int n = 5;

    struct employee emp[n];

    int i;
    for(i = 0; i < n ;i  )
    {
         emp[i] = input();
    }

    display(emp, n);

    return 0;
}

I am able to take the input properly but while printing I am getting all values as 0. Requesting help!

Thanks!

CodePudding user response:

You forgot about the return statement in the function input

//...
return e;

Also the arguments of these calls of scanf

printf("Enter Employee name: \n");
scanf("%s", &e.name);

printf("Enter employee type: \n");
scanf("%s", &e.empType);

are incorrect. You need to write

printf("Enter Employee name: \n");
scanf("s", e.name);

printf("Enter employee type: \n");
scanf("%9s", e.empType);

In general you should check that inputs were successful.

CodePudding user response:

That for loop is unneccessary - you would end up printing the output 5 times, for some reason. Also use "typedef struct", it's convenient. And don't type "&" when dealing with struct's elements. This code is a mess, by the way.

  • Related