使用 STL 算法与容器(char * 除外)进行 C++ 二进制文件 I/O

标签 c++ stl binary iterator io

我正在尝试使用 STL 复制算法对二进制文件 I/O 进行简单测试,以将数据复制到容器和二进制文件中/从容器和二进制文件中复制数据。见下文:

 1 #include <iostream>
 2 #include <iterator>
 3 #include <fstream>
 4 #include <vector>
 5 #include <algorithm>
 6 
 7 using namespace std;
 8
 9 typedef std::ostream_iterator<double> oi_t;
10 typedef std::istream_iterator<double> ii_t;
11 
12 int main () {
13
14   // generate some data to test
15   std::vector<double> vd;
16   for (int i = 0; i < 20; i++)
17   {
18     double d = rand() / 1000000.0;
19     vd.push_back(d);
20   }
21 
22   // perform output to a binary file
23   ofstream output ("temp.bin", ios::binary);
24   copy (vd.begin(), vd.end(), oi_t(output, (char *)NULL));
25   output.close();
26 
27   // input from the binary file to a container
28   std::vector<double> vi;
29   ifstream input ("temp.bin", ios::binary);
30   ii_t ii(input);
31   copy (ii, ii_t(), back_inserter(vi));
32   input.close();
33 
34   // output data to screen to verify/compare the results
35   for (int i = 0; i < vd.size(); i++)
36     printf ("%8.4f  %8.4f\n", vd[i], vi[i]);
37 
38   printf ("vd.size() = %d\tvi.size() = %d\n", vd.size(), vi.size());
39   return 0;
40 }

结果输出如下,有两个问题,据我所知:

1804.2894  1804.2985
846.9309    0.9312
1681.6928    0.6917
1714.6369    0.6420
1957.7478    0.7542
424.2383    0.2387
719.8854    0.8852
1649.7605    0.7660
596.5166    0.5171
1189.6414    0.6410
1025.2024    0.2135
1350.4900    0.4978
783.3687    0.3691
1102.5201    0.5220
2044.8978    0.9197
1967.5139    0.5114
1365.1805    0.1815
1540.3834    0.3830
304.0892    0.0891
1303.4557    0.4600
vd.size() = 20  vi.size() = 20

1) 从二进制数据读取的每个 double 都会丢失小数点之前的信息。 2) 数据在小数点后第三位(或更早)被破坏,并且引入了一些任意错误。

请提供任何帮助,我们将不胜感激。 (我希望有人能指出我之前关于此问题的帖子,因为我的搜索不足)

最佳答案

对于问题1)您需要指定一个分隔符(例如空格)。非小数部分粘在前一个数字的小数部分上。在 C++ 中,强制转换和使用 NULL 通常是错误的。应该是一个提示;)

copy (vd.begin(), vd.end(), oi_t(output, " ")); 

对于问题2)

#include <iomanip>
output << setprecision(9);

关于使用 STL 算法与容器(char * 除外)进行 C++ 二进制文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1855704/

相关文章:

c++ - C++列表/队列的顶部返回值

c - 如何将二进制数分成几部分? C语言

r - 如何将大型数据集中的 NA 转换为 0 或 1?

c++ - 如何以及在何处为 Visual C++ OpenCV 项目添加调试符号

c++ - 静态函数强制单例模式?

c++ - 相当于 C/C++ 中的 numpy.nan_to_num

c++ - 在恒定的 O(1) 时间内连接 2 个 STL vector

c++ - 返回时奇怪的 C++ 引用失效

c++ - 在 Visual Studio 2012 中调试 C++ 代码时跳过 STL 代码?

java - 协助公钥加密