0

(これは宿題です。) クラス A のオブジェクト (いくつかの文字列と int を含み、クラス B のオブジェクトのリストも含む) をファイルに書き込もうとしています。次に、これらのオブジェクトをファイルから読み戻して、その内容を表示する必要があります。私はこのコードを使用しています:

書き込み:

ofstream ofs("filestorage.bin", ios::app|ios::binary);
A d;
ofs.write((char *)&d, sizeof(d));
ofs.close();

読む:

ifstream ifs("filestorage.bin", ios::binary);
A e(1);

while(ifs.read((char *)&e, sizeof(e))) {    
    cout<<e;
}

ifs.close();

<<はすでに再定義されています。

データをファイルに書き込み、それを読み返し、必要なものをすべて表示しますが、最終的にはかなり太い「アクセス違反」エラーが発生します。また、単純な変数をファイルに読み書きしようとしました(intsなど)。それはうまくいきます。しかし、オブジェクトまたは文字列を読み取ろうとすると、「アクセス違反」が発生します。エラーが発生しないため、書き継ぎは問題ありません。

なぜこれが起こっているのか、どうすれば修正できるのか教えていただけますか? 必要に応じて、A クラスと B クラスも投稿できます。ありがとう!

4

2 に答える 2

1

<<2 つの演算子と>>をクラスに実装します。

class A {
    int a;
    string s;
pubilc:
    friend ostream& operator<< (ostream& out, A& a ) {
        out << a.a << endl;
        out << a.s << endl;
    }
    friend istream& operator>> (istream& is, A& a ) {
        //check that the stream is valid and handle appropriately.
        is >> a.a; 
        is >> a.s;
    }
};

書く:

A b;
ofstream ofs("filestorage.bin", ios::app|ios::binary);
ofs << b;

読んだ:

fstream ifs("filestorage.bin", ios::binary);
A b;
ifs >> b;
于 2012-11-06T19:10:05.077 に答える
0

ストリームのステータスを確認するだけで試すことができます

while(ifs.read((char *)&e, sizeof(e)).good()){
     cout<<e;
}
于 2012-11-06T19:17:52.090 に答える