读书人

C++文件读取有关问题

发布时间: 2012-08-13 13:21:53 作者: rapoo

C++文件读取问题
想从二进制文件中读取数据,放入结构体中,但是读取成功后,就出现exe文件停止运行,调试后,出现这种情况:请大神们看看怎么回事啊!!!

C/C++ code
#include "stdafx.h"# include<fstream># include<iostream># include<string>using namespace std;struct Student{    string id;    string name;    int age;    string sex;    string habit;};int main(){    ifstream infile("D:\\stud3.dat",ios::binary);    if(!infile)    {        cout<<"error!!!"<<endl;        exit(1);    }    int i=0;    static Student stud[3];    infile.read((char*)&stud[0],sizeof(stud));    infile.close();    for(i=0;i<2;i++)    {        cout<<stud[i].id<<'\t'<<stud[i].name<<'\t'<<stud[i].age<<'\t'<<stud[i].sex<<'\t'<<stud[i].habit<<endl;    }    return 0;}

写入文件的代码如下:
C/C++ code
# include"StdAfx.h"# include<fstream># include<string> # include<iostream>using namespace std;struct Student{    string id;    string name;    int age;    string sex;    string habit;};int main(){    ofstream outfile("D:\\stud3.dat",ios::binary);    if(!outfile)    {        cout<<"error!!!";        exit(1);    }    Student stud[3]=    {        "2010302603","wuwei",20,"man","basketball",    "2010304567","haha",21,"woman","eat","2010304564","shenme",22,"woman","play"    };    int i;    for(i=0;i<3;i++)    {        cout<<stud[i].id<<'\t'<<stud[i].name<<'\t'<<stud[i].age<<'\t'<<stud[i].sex<<'\t'<<stud[i].habit<<endl;        outfile.write((char*)&stud[i],sizeof(stud[i]));    }    outfile.close();    return 0;}




[解决办法]
探讨
已经调试好了,但是不太明白这个运行机制?能否讲解一下呢?

引用:

同意这个说法

引用:
outfile.wirte时仅输出了string存储字符串的指针地址。
因此读取时也仅是读到了地址,但是没有内容。
所以输出时会找到无效的地址,因此出错。
你最好用char id[BUFFER_SIZE]替换string

[解决办法]
探讨
我把所有的string都改成了char型数组,然后就行了,可是不太明白这个运行机制啊?求大神讲解

引用:

outfile.wirte时仅输出了string存储字符串的指针地址。
因此读取时也仅是读到了地址,但是没有内容。
所以输出时会找到无效的地址,因此出错。
你最好用char id[BUFFER_SIZE]替换string

读书人网 >C++

热点推荐