c++ - 在VC环境中,使用fwrite 写入浮点数数据异常
PHP中文网
PHP中文网 2017-04-17 13:54:11
0
3
990
#include<stdio.h>
#define SIZE 1
typedef struct
{
    float num;
    float age;
 }student;
 
student stu[SIZE];
 
void save()
{
    FILE *fp;
    int i;
    if((fp=fopen("dat.txt","w"))==NULL)
    {
        printf("无法打开此文件!\n");
        return;
    }
    for(i=0;i<SIZE;i++)
    if(fwrite(&stu[i], sizeof(student), 1, fp) != 1)
    printf("文件写入错误。!\n");
    fclose(fp);
}
 
void main()
{
    int i;
    for(i=0;i<SIZE;i++)
        scanf("%f%f",&stu[i].num,&stu[i].age);
    save();
}

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
PHPzhong

You can press F5 to debug and click Retry when the pop-up box pops up. It will jump to the point where the exception occurs. There will be an arrow on the left to mark which line caused the error.

According to the information provided here, at least one thing is definitely wrong:

    if((fp=fopen("dat.txt","w"))==NULL)

should be changed to:

    if((fp=fopen("dat.txt","wb"))==NULL)

To read and write binary files under Windows, the opening method must specify the "b" parameter. Otherwise, even if no runtime exception occurs, the file data that comes out will be incorrect.

PHPzhong

if(fwrite(&stu[i], sizeof(student), 1, fp) != 1)
应为
if(fwrite(stu[i], sizeof(student), 1, fp) != 1)

大家讲道理

~~ Judging from the above code, there is a problem with your VC6. You can try changing the machine and the test will pass

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template