簡體   English   中英

寫矢量 <double> 到二進制文件並再次讀取它

[英]Writing vector<double> to binary file and reading it again

我正在嘗試將雙向量寫入二進制文件。 這樣做后我想讀它。 這似乎不起作用。 這是代碼:

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個數字。

這個.write()接受的是字節數,而不是要寫的數:

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

由於您已經計算了正確的值,請使用它:

bestand.write(pointer, bytes );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM