|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 海绵爱上星 于 2018-9-1 17:47 编辑
代码如下:
问题在代码的注释里 ,在函数 show() 部分 :
#include <stdio.h>
#include <stdlib.h>
struct student
{
int num;
char name[20];
double eng;
double math;
double chi;
double sum;
};
struct student stu[50];
#define LEN sizeof(struct student)
#define FORMAT "%d\t%s\t%8.1lf\t%8.1lf\t%8.1lf\t%8.1lf\n"
#define DATA stu[i].num,stu[i].name,stu[i].eng,stu[i].math,stu[i].chi,stu[i].sum
int menu();
void show();
void input();
int main()
{
int number;
system("color f0\0");
printf("Welcome to my management!\n");
menu();
printf("请选择(0-8):");
scanf("%d",&number);
while(number)
{
switch(number)
{
case 1:
{
input();
break;
}
case 8:
{
show();
break;
}
case 0:
{
exit(0);
}
}
printf("请选择(0-8):");
scanf("%d",&number);
}
return 0;
}
//show
int menu()
{
printf("------student Information ------\n");
printf("\t\t\t1. Information Input\n");
printf("\t\t\t2. Seek Information\n");
printf("\t\t\t3. Delete Information\n");
printf("\t\t\t4. Modify Information\n");
printf("\t\t\t5. Insert Student Information\n");
printf("\t\t\t6. Order by Student number\n");
printf("\t\t\t8. Show Message\n");
printf("\t\t\t0. Exit\n");
return 0;
}
// 8___show
void show()
{
FILE *fp;
int i,m=0;
fp = fopen("data.txt","r");
//已经存到磁盘里,从磁盘里读出
if(fp==NULL)
{
printf("文件打开失败!\n");
return;
}
while(!feof(fp)) //没到文件结尾才能进入循环
{
if(fread(&stu[m],LEN,1,fp)==1) //读取LEN ( = sizeof(struct student ) 长度的字节, 读取成功返回1??)
{
m++;
}
else /****** 没到文件结尾才才能进入while循环,但是为什么读取失败了啊? 返回值不是 1 吗??? ********/
{
printf("文件打开失败!");
printf("呵呵\n");
return;
}
}
fclose(fp);
//打印
printf("学号\t姓名\t语文\t数学\t外语\n");
//m个同学需要打印
for(i=0;i<m;i++)
{
printf(FORMAT,DATA);
}
}
// 1___input Information
void input()
{
int i,m=0;
char ch[2];
FILE *fp;
if((fp=fopen("data.txt","a+"))==NULL)
{
printf("文件不存在!\n");
return;
}
while(!feof(fp))
{
if(fread(&stu[m],LEN,1,fp)==1)
{
m++;
}
}
//共m个数据
if(m==0)
{
printf("文件里没有数据!\n");
}
else
{
show();
}
fclose(fp);
if(fopen("data.txt","a+")==NULL)
{
printf("文件打开失败!\n");
return;
}
//输入数据
printf("是否录入数据?(y / n):");
scanf("%s",ch);
while(strcmp(ch,"y")==0||strcmp(ch,"Y")==0)
{
printf("输入要录入的学号:");
scanf("%d",&stu[m].num);
for(i=0;i<m;i++)
{
if(stu[i].num==stu[m].num)
{
printf("学号已经存在!\n");
return;
}
}
//学号不重复
printf("姓名:");
scanf("%s",stu[m].name);
printf("eng:");
scanf("%lf",&stu[m].eng);
printf("math:");
scanf("%lf",&stu[m].math);
printf("chi:");
scanf("%lf",&stu[m].chi);
stu[m].sum = stu[m].eng+stu[m].math+stu[m].chi;
if(fwrite(&stu[m],LEN,1,fp)!=1)
{
printf("保存失败!\n");
return;
}
else
{
printf("%s 已经保存!\n",stu[m].name);
m++;
}
printf("continue?(y / n):");
scanf("%s",ch);
}
fclose(fp);
printf("ok!\n");
}
|
|