【问题标题】:Writing vector<double> to binary file and reading it again将 vector<double> 写入二进制文件并再次读取
【发布时间】:2012-11-02 03:20:03
【问题描述】:

我正在尝试将双精度向量写入二进制文件。 这样做之后,我想阅读它。这似乎不起作用。 代码如下:

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() 大小参数不正确。应该是v.size() * sizeof(double)
  • @K-ballo skipws 不适用于未格式化的输入。

标签: c++ file vector binary


【解决方案1】:

这个.write()bytes 的数量,而不是要写入的items 的数量:

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

既然您已经计算出正确的值,请使用它:

bestand.write(pointer, bytes );

【讨论】:

  • 这工作谢谢!假设我有一个 for 循环,每次迭代都将一个新向量 写入同一个文件。我必须改变什么来阅读?但这也是在 for 循环中?
  • 好的 nvm 我想通了 :)。谢谢
猜你喜欢
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多