int i; typedef struct student { int num; char name[20]; int score[3]; float avg; }student; void Inputdata(student* stu) { printf("请输入新学生的信息:\n"); printf("num name s1 s2 s3\n"); scanf("%d %s %d %d %d", &(stu->num), stu->name, &(stu->score[0]), &(stu->score[1]), &(stu->score[2])); stu->avg = (stu->score[0] + stu->score[1] + stu->score[2]) / 3.0; } void readdate(student stu[]) { FILE* fp = fopen("stu_ sort.txt", "r"); if (fp == NULL) { printf("read stu_ sort file error!"); return -1; } for (i = 0; i < 5; i++)//从文件中读入数据 { fscanf(fp, "%d %s %d %d %d %f", &stu[i].num, stu[i].name, &stu[i].score[0], &stu[i].score[1], &stu[i].score[2], &stu[i].avg); } fclose(fp); } void Insertdata(student* oldstu, student* newstu,int n) { int pos = 0; while (pos < n) { if ((newstu->avg) < (oldstu[pos].avg)) break; pos++; } for (i = n; i > pos; i--) { memcpy(&oldstu[i],&oldstu[i-1], sizeof(student)); } memcpy(&oldstu[pos], newstu, sizeof(student)); } void writedate(student* stu) { FILE* fp = fopen("stu_new_sort.txt", "w"); if (fp == NULL) { printf("write file error!"); return -1; } for (i = 0; i < 6; i++)//使用fprint函数将结构体数组stu中的数据写入fp { fprintf(fp, "%d %s %d %d %d %f\n", stu[i].num, stu[i].name, stu[i].score[0], stu[i].score[1], stu[i].score[2], stu[i].avg); } fclose(fp); } int main() { student newstu;//首先定义一个新学生信息 Inputdata(&newstu);//输入这个新学生的信息 student oldstu[6]; readdate(oldstu);//调用函数从上一题排好序的文件中读入5个学生数据 Insertdata(oldstu, &newstu,5);//把新数据有序地插入到老数组中 writedate(oldstu);//把含有新数据的数组写入到新文件 return 0; }改写成正确的
时间: 2023-12-11 13:03:21 浏览: 98
int i;
typedef struct student {
int num;
char name[20];
int score[3];
float avg;
} student;
void Inputdata(student* stu) {
printf("请输入新学生的信息:\n");
printf("num name s1 s2 s3\n");
scanf("%d %s %d %d %d", &(stu->num), stu->name, &(stu->score[0]), &(stu->score[1]), &(stu->score[2]));
stu->avg = (stu->score[0] + stu->score[1] + stu->score[2]) / 3.0;
}
int readdate(student stu[]) {
FILE* fp = fopen("stu_sort.txt", "r");
if (fp == NULL) {
printf("read stu_sort file error!");
return -1;
}
for (i = 0; i < 5; i++) {
fscanf(fp, "%d %s %d %d %d %f", &stu[i].num, stu[i].name, &stu[i].score[0], &stu[i].score[1], &stu[i].score[2], &stu[i].avg);
}
fclose(fp);
return 0;
}
void Insertdata(student* oldstu, student* newstu, int n) {
int pos = 0;
while (pos < n) {
if ((newstu->avg) < (oldstu[pos].avg))
break;
pos++;
}
for (i = n; i > pos; i--) {
memcpy(&oldstu[i], &oldstu[i - 1], sizeof(student));
}
memcpy(&oldstu[pos], newstu, sizeof(student));
}
int writedate(student* stu) {
FILE* fp = fopen("stu_new_sort.txt", "w");
if (fp == NULL) {
printf("write file error!");
return -1;
}
for (i = 0; i < 6; i++) {
fprintf(fp, "%d %s %d %d %d %f\n", stu[i].num, stu[i].name, stu[i].score[0], stu[i].score[1], stu[i].score[2], stu[i].avg);
}
fclose(fp);
return 0;
}
int main() {
student newstu;
Inputdata(&newstu);
student oldstu[6];
if (readdate(oldstu) == -1) {
return -1;
}
Insertdata(oldstu, &newstu, 5);
if (writedate(oldstu) == -1) {
return -1;
}
return 0;
}
阅读全文