C语言中memset()如何用?下面的程序运行时为什么在文件中显示的age信息都是乱码?

C语言中memset()如何用?下面的程序运行时为什么在文件中显示的age信息都是乱码? 如何改正?
#include
#include
#define N 3
void main()
{
typedef struct student
{
char id[6];
char name[8];
int age;
}STU;
FILE *fp;
STU stu1[N],stu2[N];
if((fp=fopen("d:\student.txt","wb"))==NULL)
{
printf("cannot open this file\n");
exit(0);
}
for(int i=0;i<N;i++)
{ memset(&stu1[i], 0, sizeof( struct student));
printf("请输入第%d个学生的信息\n",i+1);
scanf("%s %s %d",stu1[i].id,stu1[i].name ,&stu1[i].age );
fwrite(stu1+i,sizeof(STU),1,fp);
}
fclose(fp);
if((fp=fopen("d:\student.txt","rb"))==NULL)
{
printf("cannot open this file\n");
exit(0);
}
for(int j=0;j<N;j++)
{
memset(&stu2[j], 0, sizeof( struct student));
printf("\n");
fread(stu2+j,sizeof(STU),1,fp);
printf("第%d个学生的信息\n",j+1);
printf("%s\t %s\t %d\n",stu2[j].id,stu2[j].name,stu2[j].age);

}
fclose(fp);
}
运行:

图片说明

文件中显示结果:

图片说明

年龄对应的为什么是乱码?

因为你存的是整数,在计算机中它以原始值而不是ascii表示。如果要可读,需要定义成char类型,用itoa转换。

ID可以定义成 char,为什么年龄不也一样定义成 char?这样,处理就统一了。

比如1的ascii码是49
你在文件中存49,读出来的是"1"
如果你存的是1,那么读出来的其实是4个不可见的字符

这种问题中学计算机课都应该学过的。