該程序的工作原理是在開始時打印垃圾值(ch = 2)並打印兩次相同的輸出。 我使用這個爲我的project.It包含更多的數據,在那裏我用一個單一的對象,而不是數組對象。它沒有工作。 數組的每個對象都存儲一組數據。在讀取和寫入文件時出錯
#include<iostream>
#include<fstream>
using namespace std;
class rw //a class containing some data
{
public:
int n;
char a;
};
int main()
{
int i;
rw r[2]; //an array of objects
int ch;
fstream f1;
f1.open("file1.txt",ios::in|ios::out|ios::ate);
cout<<"1-read,2-write";
cin>>ch;
f1.seekp(0,ios::beg);
if(ch==1)//for saving
{
r[0].n=1;
r[0].a='a';
f1.write((char*) &r[0],sizeof(r[0]));
r[1].n=2;
r[1].a='b';
f1.write((char*)&r[1],sizeof(r[1]));
}
if(ch==2)//for reading
{
f1.seekg(0,ios::beg);
while(!f1.eof())
{
i=0;
cout<<r[i].n<<r[i].a;
cout<<"\n";
f1.read((char*)&r[i],sizeof(r[i]));
i++;
}
}
system("pause");
return 0;
}
你是什麼意思'沒有工作',請你能詳細說明一下嗎?程序崩潰了嗎?它只是不寫出文件? – cybermonkey 2014-11-05 09:01:33