编制一个C/C++程序设计语言成绩记录簿,每个学生信息包括:学号、姓名、C语言成绩。具体功能: (1)创建信息链表并以磁盘文件保存
时间: 2024-05-08 10:19:24 浏览: 100
学生籍贯信息记录簿(1)创建信息链表并以磁盘文件保存;
5星 · 资源好评率100%
我很乐意帮您解答这个问题,以下是可能的程序设计实现:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct student {
char id[10];
char name[20];
int score;
struct student *next;
} Student;
void insert(Student **head, char *id, char *name, int score) {
Student *new_student = (Student *)malloc(sizeof(Student));
strcpy(new_student->id, id);
strcpy(new_student->name, name);
new_student->score = score;
new_student->next = NULL;
if (*head == NULL) {
*head = new_student;
} else {
Student *p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = new_student;
}
}
void save(Student *head) {
FILE *fp = fopen("score.txt", "w");
if (fp != NULL) {
Student *p = head;
while (p != NULL) {
fprintf(fp, "%s %s %d\n", p->id, p->name, p->score);
p = p->next;
}
fclose(fp);
} else {
printf("Error: Unable to save file.\n");
}
}
int main() {
Student *head = NULL;
// example usage
insert(&head, "10001", "张三", 80);
insert(&head, "10002", "李四", 90);
insert(&head, "10003", "王五", 85);
save(head);
// free memory
Student *p = head;
while (p != NULL) {
Student *tmp = p;
p = p->next;
free(tmp);
}
return 0;
}
```
此程序使用链表来保存学生信息,可以插入新的学生,以及将信息保存到磁盘文件中(score.txt)。需要注意的是,此程序只是一种参考实现,您可以自行进行修改和优化。
阅读全文