我创建了一个有两个字符串对象的类。此类在二进制模式中向/从文件中写入和读取两个字符串对象。所有这些都在头文件" a_details.h"中定义。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class AVENGERS{
public:
string codename;
string realname;
const size_t JUMP = 2*sizeof(string);
AVENGERS(string code=" ",string real=" "){codename=code;realname=real;}
void read(istream & is){
is.read((char*)&codename,sizeof(string));
is.read((char*)&realname,sizeof(string));
}
void write(ostream & os){
os.write((char*)&codename,sizeof(string));
os.write((char*)&realname,sizeof(string));
}
};
istream & operator >> (istream & is,AVENGERS & A)
{
is>>A.codename>>A.realname;
return is;
}
ostream & operator << (ostream & os,AVENGERS & A)
{
os<<A.codename<<"-"<<A.realname;
return os;
}
下面是文件&#34; a_write.cpp&#34;它以二进制模式打开文件并写入3个AVENGERS对象(因此,6个字符串)。
#include <iostream>
#include <fstream>
#include <string>
#include "a_details.h"
using namespace std;
int main(){
fstream ffile("avengers.bin", ios_base::binary | ios_base::in |ios_base::out);
if(ffile.is_open()){
AVENGERS("Iron Man","Tony Stark").write(ffile);
AVENGERS("Captain America","Steve Rogers").write(ffile);
AVENGERS("Hulk","Bruce Banner").write(ffile);
cout<<"writing done\n";
ffile.close();
}
}
之后,我检查了avengers.bin的大小是24个字节,以验证写操作是否正确完成。但是,当我创建另一个文件时 &#34; a_read.cpp&#34;读入数据,它给了我错误。下面是代码。
#include <iostream>
#include <fstream>
#include <string>
#include "a_details.h"
using namespace std;
int main(){
fstream ffile("avengers.bin" , ios_base::binary | ios_base :: in |ios_base::out);
if(ffile.is_open()){
cout<<"file is going to open"<<endl;
while(!ffile.eof())
{
cout<<"entered loop\n";
AVENGERS TEMPO(" "," ");
TEMPO.read(ffile);
cout<<"read data\n";
if(ffile.gcount()==0)break;
cout<<"this means file is not at end of file\n";
}
cout<<"this means file is at end of file\n";
ffile.close();
}
cout<<"reading done";
return 0;
}
之间的cout语句供我参考,因为我想查看问题所在。但我无法理解。 程序循环1次,然后崩溃。 有人能帮帮我吗? This is the Error message