来人帮忙看下,谢谢!
程序目的是将5个学生的数据写入stud文件,便是将N设成5以上的数,结果是乱码,5以下的话结果显示却是正常的,不知道怎么回事,帮忙看下谢谢了!!#define N 5
#define M 3
#include<stdio.h>
#define LEN sizeof(struct student)
struct student
{int num;
char name[10];
float score[3];
float aver;
}; 这里改成}stu[N];|
main() |
{int i,j; |这样就对了,为什么两种定义结果不一样??
float s; |
struct student stu[N]; 这里去掉 |
FILE *fp;
for(i=0;i<N;i++)
{printf("\nNO.:");
scanf("%d",&stu[i].num);
printf("name:");
getchar();
gets(stu[i].name);
for(j=0,s=0.0;j<M;j++)
{printf("score%d:",j+1);
scanf("%f",&stu[i].score[j]);
s=s+stu[i].score[j];
}
stu[i].aver=s/3.0;
}
if((fp=fopen("stud","w"))==NULL)
{printf("can not find the file\n");
exit(0);
}
for(i=0;i<N;i++)
if(fwrite(&stu[i],LEN,1,fp)!=1)
printf("File write error\n");
fclose(fp);
fp=fopen("stud","r");
printf("\nNO. name score1 score2 score3 aver\n");
for(i=0;i<N;i++)
{fread(&stu[i],LEN,1,fp);
printf("%-3d",stu[i].num);
printf("%8s",stu[i].name);
for(j=0;j<M;j++)
printf("%10.2f",stu[i].score[j]);
printf("%8.2f",stu[i].aver);
printf("\n");
}
fclose(fp);
}
[[it] 本帖最后由 zgzhly 于 2008-12-13 19:30 编辑 [/it]]