5

double のベクトルをバイナリ ファイルに書き込もうとしています。これをやった後、私はそれを読みたいです。これはうまくいかないようです。コードは次のとおりです。

ofstream bestand;
vector<double> v (32);
const char* pointer = reinterpret_cast<const char*>(&v[0]);
size_t bytes = v.size() * sizeof(v[0]);
bestand.open("test",ios::out | ios::binary);
for(int i = 0; i < 32; i++)
{
   v[i] = i;
   cout << i;
   }
bestand.write(pointer, v.size());
bestand.close();
ifstream inlezen;
vector<double> v2 (32);
inlezen.open("test", ios::in | ios::binary);
char byte[8];
bytes = v2.size() * sizeof(v2[0]);
inlezen.read(reinterpret_cast<char*>(&v2[0]), bytes);
for(int i =0; i < 32; i++){

 cout << endl << v2[i] << endl;
 }

これは「0 1 2 3 0 0 0......」を出力するので、最初の 4 つの数字を正しく読み取っているようです。

4

1 に答える 1

7

これは、書き込む項目数ではなく、バイト.write()数を取ります。

bestand.write(pointer, v.size());

すでに正しい値を計算しているので、それを使用します。

bestand.write(pointer, bytes );
于 2012-11-13T16:59:18.080 に答える