简体   繁体   中英

How to use Structures to print this output in C program?

Output Should be:

Please enter employee's id: 1
Please enter your full name: Jane Doe
Please enter employee's salary: 98500.9718
Employee 1 is set successfully

Please enter employee's id: 2
Please enter your full name: John Doe
Please enter employee's salary: 96500.8723
Employee 2 is set successfully

Employee 1
Name - Jane Doe
Salary - 98500.97

Employee 2
Name - John Doe
Salary - 96500.87` 

My Code:

#include <stdio.h>
#include <string.h>
#define SIZE 2

struct Employee
{
int id;
char fullName[32];
double salary;
};

void setEmployee(struct Employee *);
void getFullName(char *);
void getId(int *);
void setSalary(double *);
void printEmployee(const struct Employee *);
void flushKeyboard()
{
    while (getchar() != '\n');
}

int main(void)
{
    struct Employee Employees[SIZE];
    int i = 0;
    for (i = 0;i < SIZE;i++)
    {
    setEmployee(Employees);
}
for (i = 0;i < SIZE;i++) {
    printEmployee(Employees);
}

return 0;
}
void setEmployee(struct Employee *employee1)
{
    getId(&employee1->id);
    getFullName(&employee1->fullName);
    setSalary(&employee1->salary);
    printf("Employee %d is set successfully\n\n", (employee1->id));

}
void getFullName(char *name1)
{
    printf("Please enter your full name: ");
    scanf(" %31[^\n]", name1);
flushKeyboard();

}
void getId(int *identity)
{
    printf("Please enter employee's id: ");
    scanf("%d", &identity);

}
void setSalary(double *salary)
{
    printf("Please enter employee's salary: ");
    scanf("%lf", salary);

}
void printEmployee(const struct Employee *final)
{
        printf("Employee: %d\n", final->id);
        printf("Name: %s\n", final->fullName);
        printf("Salary: %.2lf\n\n", final->salary);
}

After running this whole code, my output only shows the values that the user enters for the second for loop. So the values will be the same. The employee number, Name and salary will be same instead of giving me 2 seperate values that user enters. My question is why does it keep giving me same value? I would use a for loop but i am not allowed to use a for loop for some reason.

for (i = 0;i < SIZE;i++) { printEmployee(Employees); }

Here you have forgotten to use your counting variable->

for (i = 0;i < SIZE;i++) { printEmployee(&Employees[i]); } 

What happens when you pass the whole array like that is, that the array decayes to a pointer to the first element in the array which is fine for the function because it expects a pointer to an Employee struct. But then it only prints the first enployee in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM