今天用vc++做文件的写入和读取练习时,程序为
struct stu
{
char name[15];
char num[6];
float score[2];
}student;
int main(void)
{
FILE* fp;
int i;
if(NULL == (fp = fopen("./1.txt", "wb")))
{
printf("File 1.txt cannot be openned!\n");
return 0;
}
printf("plese input:\nname\nnum\nscore\nscore\n");
for(i=0; i<3; i++)
{
scanf("%s %s %f %f", student.name, student.num, &student.score[0], &student.score[1]);
fwrite(&student, sizeof(student), 1, fp);
}
fclose(fp);
return 0;
}
然后编译没有任何错误,但是运行时候只输入一个数据结构就出现Debug Error, runtime error。
断点调试发现到scanf就出现错误,怎么改也不好,但是在vs2010中就没有错误正确运行,于是各种查资料发现有两种改法
1、把float改成double
2、在scanf之前给float类型的变量赋初值