设有若干个人员的数据,其中有学生和教师。学生的数据中包括:姓名、号码、性别、职业、班级。教师的数据包括:姓名、号码、性别、职业、职务。要求用C语言输入人员的数据,然后再输出
时间: 2023-07-10 19:20:29 浏览: 82
python 编写input()和output()函数输入,输出5个学生的数据记录(示例)
这些人员的数据,其中学生的数据按照班级排序,教师的数据按照职务排序。以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
char name[20];
int id;
char sex;
char profession[20];
int class;
};
struct teacher {
char name[20];
int id;
char sex;
char profession[20];
char duty[20];
};
int cmp_student(const void *a, const void *b) {
struct student *pa = (struct student *)a;
struct student *pb = (struct student *)b;
return pa->class - pb->class;
}
int cmp_teacher(const void *a, const void *b) {
struct teacher *pa = (struct teacher *)a;
struct teacher *pb = (struct teacher *)b;
return strcmp(pa->duty, pb->duty);
}
int main() {
int n, i;
printf("请输入人员数量:");
scanf("%d", &n);
struct student *students = malloc(sizeof(struct student) * n);
struct teacher *teachers = malloc(sizeof(struct teacher) * n);
for (i = 0; i < n; i++) {
printf("请输入第%d个人的信息:\n", i+1);
char type[10];
scanf("%s", type);
if (strcmp(type, "学生") == 0) {
scanf("%s %d %c %s %d", students[i].name, &students[i].id, &students[i].sex, students[i].profession, &students[i].class);
} else if (strcmp(type, "教师") == 0) {
scanf("%s %d %c %s %s", teachers[i].name, &teachers[i].id, &teachers[i].sex, teachers[i].profession, teachers[i].duty);
} else {
printf("输入错误,请重新输入!\n");
i--;
}
}
qsort(students, n, sizeof(struct student), cmp_student);
qsort(teachers, n, sizeof(struct teacher), cmp_teacher);
printf("学生信息:\n");
for (i = 0; i < n; i++) {
printf("%s %d %c %s %d\n", students[i].name, students[i].id, students[i].sex, students[i].profession, students[i].class);
}
printf("教师信息:\n");
for (i = 0; i < n; i++) {
printf("%s %d %c %s %s\n", teachers[i].name, teachers[i].id, teachers[i].sex, teachers[i].profession, teachers[i].duty);
}
free(students);
free(teachers);
return 0;
}
```
注意,这里使用了结构体来存储学生和教师的数据,使用了 `qsort` 函数来对数组进行排序,其中 `cmp_student` 和 `cmp_teacher` 分别是学生和教师的比较函数。在输入时,我们先输入人员类型,再根据类型输入对应的信息。最后输出时,我们分别按照班级和职务排序,然后输出学生和教师的信息。
阅读全文