创建结构体里面包含学生的各种信息。
struct xs {
int xh;
char xm[20];
int gs, yy, wl;
double pj;
struct xs* next;
};
创建菜单
void menu()
{
printf("\n************************************\n");
printf("* 学生管理系统(1.0) *\n");
printf(" ************************************\n");
printf(" ************************************\n");
printf("* 1.创建链表 *\n");
printf("* 2.显示链表 *\n");
printf("* 3.保存文件 *\n");
printf("* 4.读取文件 *\n");
printf("* 5.系统退出 *\n");
printf(" ************************************\n");
printf("* 请选择操作:(1-5) *\n");
printf(" ************************************\n");
}
创建链表
struct xs* create()
{
struct xs* hd = (struct xs*)malloc(sizeof(struct xs)), * p = NULL, * r = NULL;
hd->next = NULL;
r = hd;
printf("请输入学生人数: ");
scanf("%d", &rs);
for (int i = 1; i <= rs; i++)
{
printf("请输入第%d个学生成绩信息: \n", i);
p = (struct xs*)malloc(sizeof(struct xs));
p->next = NULL;
printf("学号:");
scanf("%d", &p->xh);
printf("姓名:");
scanf("%s", &p->xm);
printf("高数:");
scanf("%d", &p->gs);
printf("英语:");
scanf("%d", &p->yy);
printf("物理:");
scanf("%d", &p->wl);
p->pj = (p->gs + p->yy + p->wl) / 3.0;
r->next = p;
r = r->next;
}
printf("创建链表完毕,请按任意键继续!\n");
_getch();
return hd;
}
打印信息
void print(struct xs* hd)
{
if (hd == NULL)
{
printf("当前链表为空,请按任意键继续!");
_getch();
return;
}
struct xs* p = hd->next;
printf(" 学号 姓名 高数 英语 物理 平均 \n");
printf(" ************************************\n");
while (p != NULL)
{
printf(" %d% -6s %d %d% d %.2f\n", p->xh, p->xm, p->gs, p->yy, p->wl, p->pj);
p = p->next;
}
printf(" ************************************\n");
printf("链表显示完毕,请按任意键继续!\n");
_getch();
}
数据保存
void save(struct xs* hd)
{
if (hd == NULL)
printf("当前链表为空,请按任意键继续!");
else
{
struct xs* p = NULL;
FILE* fp = fopen("1.txt", "w");
fprintf(fp, "%d\n", rs);
p = hd->next;
while (p != NULL)
{
fprintf(fp, "%d%s%d%d%d%lf\n", p->xh, p->xm, p->yy, p->wl, p->pj);
p = p->next;
}
fclose(fp);
printf("数据保存结束,请按任意键继续!\n");
}
_getch();
}
读取文件
struct xs* read()
{
struct xs* hd = (struct xs*)malloc(sizeof(struct xs)), * p = NULL, * r = NULL;
FILE* fp = fopen("1.txt", "r");
hd->next = NULL;
r = hd;
fscanf(fp, "%d\n", &rs);
for (int i = 1; i <= rs; i++)
{
p = (struct xs*)malloc(sizeof(struct xs));
fscanf(fp, "%d%s%d%d%d%lf\n", &p->xh, p->xm, &p->gs, &p->yy, &p->wl, &p->pj);
p->next = NULL;
r->next = p;
r = r->next;
}
printf("读取文件结束,请按任意键继续!\n");
_getch();
return hd;
}
释放资源
void sflb(struct xs* hd)
{
struct xs* p = NULL;
while (hd != NULL && hd->next != NULL)
{
p = hd->next;
hd->next = p->next;
free(p);
}
free(hd);
}
主函数
void main()
{
struct xs* head = NULL;
int xz;
do
{
system("cls");
menu();
scanf("%d", &xz);
switch (xz)
{
case 1:sflb(head); head = create(); break;
case 2:print(head); break;
case 3:save(head); break;
case 4:sflb(head); head = read(); break;
case 5:sflb(head);
}
} while (xz != 5);
}