c语言习题,员工记录?

编写程序,创建包含有工号、姓名、省、市、薪水五个成员项的员工记录,由键盘输入3个员工记录后以表单形式输出这3个记录。注意省和市简短名称输入,每项不超过4个汉字,程序最终要将这两项合并为一个串输出。

以下是一个示例C语言程序,可以实现员工记录的输入和输出:
#include <stdio.h>
#include <string.h>
struct Employee {
int empno;
char name[20];
char province[5];
char city[5];
int salary;
};
int main() {
struct Employee employees[3];
int i;
for (i = 0; i < 3; i++) {
printf("请输入员工 %d 的信息:\n", i + 1);
printf("工号:");
scanf("%d", &employees[i].empno);
printf("姓名:");
scanf("%s", employees[i].name);
printf("省份简称:");
scanf("%s", employees[i].province);
printf("城市简称:");
scanf("%s", employees[i].city);
printf("薪水:");
scanf("%d", &employees[i].salary);
}
printf("\n员工记录如下:\n");
printf("%-10s %-8s %-8s %s\n", "工号", "姓名", "省份", "薪水");
for (i = 0; i < 3; i++) {
char location[10];
strcpy(location, employees[i].province);
strcat(location, employees[i].city);
printf("%-10d %-8s %-8s %d\n", employees[i].empno, employees[i].name, location, employees[i].salary);
}
return 0;
}
在这个程序中,我们定义了一个结构体 Employee,包含了工号、姓名、省份简称、城市简称和薪水五个成员项。我们使用一个数组 employees 来存储三个员工的信息。
在输入员工信息时,我们使用 scanf 函数分别输入每个成员项的值。
在输出员工信息时,我们首先输出一个表头,然后使用循环逐个输出每个员工的信息。对于省份和城市,我们将它们合并为一个串后输出,使用了 strcpy 和 strcat 函数。在输出时,我们使用了格式化字符串 %s,将其作为一个整体输出。
这样,我们就完成了这道题目的编写,实现了员工记录的输入和输出。
温馨提示:答案为网友推荐,仅供参考
第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,表示程序正常结束。
相似回答
大家正在搜