代码
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void Save();struct SUser
{int nNumb;char sName[20];float fMath;
}g_user[100];void Print()
{puts("\n学号\t姓名\t数学");int i = 0;while (g_user[i].nNumb){if(g_user[i].nNumb>0)printf("%d\t%s\t%0.1f\n", g_user[i].nNumb, g_user[i].sName, g_user[i].fMath);++i;}printf("\n\t总共有%d条学生信息\n\n", i);
}int Check(int nNumb)
{int i = 0;while (g_user[i].nNumb){if (nNumb == g_user[i].nNumb)return 1;++i;}return 0;
}void Add()
{int nNumb;printf("请输入学号:");scanf_s("%d", &nNumb);while (Check(nNumb)){printf("该学号已存在,请重新输入(0取消输入):");scanf_s("%d", &nNumb);if (nNumb == 0)return;}int i = 0;while (g_user[i].nNumb>0)++i;g_user[i].nNumb = nNumb;printf("请输入姓名:");scanf_s("%s", g_user[i].sName,sizeof(g_user[i].sName));printf("请输入成绩:");scanf_s("%f", &g_user[i].fMath);Save();Print();
}void Delete()
{printf("请输入要删除的学号:");int nNumb;scanf_s("%d", &nNumb);int i = 0;while (g_user[i].nNumb){if (g_user[i].nNumb == nNumb){g_user[i].nNumb = -1;break;}++i;}if (g_user[i].nNumb!=-1)puts("你输入的学号不存在!");else{Save();Print();}
}void Modify()
{printf("请输入要修改的学号:");int nNumb;scanf_s("%d", &nNumb);int i = 0;while (g_user[i].nNumb){if (g_user[i].nNumb == nNumb){printf("%d\t%s\t%0.1f\n", g_user[i].nNumb, g_user[i].sName, g_user[i].fMath);printf("请输入新的姓名:");scanf_s("%s", g_user[i].sName, sizeof(g_user[i].sName));printf("请输入新的成绩:");scanf_s("%f", &g_user[i].fMath);return;}++i;}Save();Print();
}void Load()
{FILE* pf = fopen("data.lv", "r");if (!pf)return;int i = 0;while (fread(&g_user[i], 1, sizeof(SUser), pf) == sizeof(SUser))++i;fclose(pf);
}void Save()
{FILE* pf = fopen("data.lv", "w");if (!pf){puts("保存数据时失败!");return;}int i = 0;while (g_user[i].nNumb){if (-1 != g_user[i].nNumb)fwrite(&g_user[i], 1, sizeof(SUser), pf);++i;}fclose(pf);
}int Judge(int nIndex,int j)
{if (nIndex == 1)return g_user[j].nNumb > g_user[j + 1].nNumb;if (nIndex == 2)return strcmp(g_user[j].sName, g_user[j + 1].sName) > 0;if (nIndex == 3)return g_user[j].fMath < g_user[j + 1].fMath;return 0;
}void Sort(int nIndex)
{int i = 0, n = 0;while (g_user[i++].nNumb)++n;i = 0;int flag = 0;while (i < n - 1){int j = 0;while (j < n - 1 - i){if(Judge(nIndex,j)){SUser t = g_user[j];g_user[j] = g_user[j + 1];g_user[j + 1] = t;}++j;}++i;}
}int DispMenu()
{puts("1.按学号排序");puts("2.按姓名排序");puts("3.按成绩排序");puts("0.返回主菜单");printf("请选择:");int i = 0;scanf_s("%d", &i);switch (i){case 1:case 2:case 3:Sort(i);Print();break;}return i;
}int Menu()
{int i = 0;puts("1.浏览所有信息");puts("2.添加信息");puts("3.删除信息");puts("4.修改信息");puts("5.查找信息");puts("0.退出");printf("请选择:");scanf_s("%d", &i);switch (i){case 0:break;case 1:while (DispMenu());Print();break;case 2:Add();break;case 3:Delete();break;case 4:Modify();break;}return i;
}int main()
{system("color 3f");Load();while (Menu());return 0;
}
运行结果