繁体   English   中英

如何使用结构在C程序中打印此输出?

[英]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` 

我的代码:

#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);
}

运行完整个代码后,我的输出仅显示用户为第二个for循环输入的值。 因此,值将相同。 员工编号,姓名和薪水将相同,而不是给我2个用户输入的单独值。 我的问题是,为什么它继续给我同样的价值? 我会使用for循环,但是由于某些原因我不允许使用for循环。

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

在这里,您忘记了使用计数变量->

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

当您像这样传递整个数组时,会发生什么情况,即该数组衰减为指向数组中第一个元素的指针 ,这对函数很合适,因为它需要指向Employee结构的指针。 但随后,它仅打印阵列中的第一个员工。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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