第1个回答 2023-02-17
#include
#include
#define MAX_NAME_LEN 20
#define MAX_LOC_LEN 8
#define MAX_RECORDS 3
struct Employee {
int emp_id;
char name[MAX_NAME_LEN];
char province[MAX_LOC_LEN];
char city[MAX_LOC_LEN];
float salary;
};
int main() {
struct Employee records[MAX_RECORDS];
// input employee records
for (int i = 0; i < MAX_RECORDS; i++) {
printf("Enter employee #%d's information:\n", i+1);
printf("Employee ID: ");
scanf("%d", &records[i].emp_id);
printf("Name: ");
scanf("%s", records[i].name);
printf("Province: ");
scanf("%s", records[i].province);
printf("City: ");
scanf("%s", records[i].city);
printf("Salary: ");
scanf("%f", &records[i].salary);
}
// print employee records in table format
printf("\nEmployee Records\n");
printf("-----------------\n");
printf("%-10s%-15s%-10s%-10s%-10s\n", "Emp ID", "Name", "Province", "City", "Salary");
for (int i = 0; i < MAX_RECORDS; i++) {
char location[MAX_LOC_LEN * 2 + 1];
strcpy(location, records[i].province);
strcat(location, records[i].city);
printf("%-10d%-15s%-10s%-10s%-10.2f\n", records[i].emp_id, records[i].name, location, "", records[i].salary);
}
return 0;
}
上面的程序中,我们首先定义了一个名为Employee的结构体,它包含了工号、姓名、省、市和薪水五个成员项。然后我们定义了一个长度为3的数组records来存储三个员工记录。
在输入员工记录时,我们使用一个循环来依次读取每个记录,并将其存储在records数组中。在输入省和市名称时,我们使用scanf函数读取字符串,然后将其合并为一个字符串,并将其存储在location变量中。
在打印员工记录时,我们首先输出一个表头,然后使用一个循环来依次输出每个记录。在输出省和市名称时,我们将它们合并为一个字符串,并使用printf函数的格式化字符串来控制输出的宽度和对齐方式。
最后,我们在主函数中返回0,表示程序正常结束。