double 型数组中保存有如下数据:1.23,69.88,34.45,67.98,2345.67。将数据以二进制形式保存到文件中去。
时间: 2024-03-05 12:51:18 浏览: 44
可以按照以下步骤进行:
1. 打开文件并以二进制写入模式打开它:
```c++
#include <fstream>
using namespace std;
double data[] = {1.23, 69.88, 34.45, 67.98, 2345.67};
ofstream out("data.bin", ios::out | ios::binary);
```
2. 循环遍历数组,将每个 double 值以二进制形式写入文件中:
```c++
for (int i = 0; i < 5; i++) {
out.write(reinterpret_cast<const char*>(&data[i]), sizeof(double));
}
```
3. 关闭文件:
```c++
out.close();
```
完整代码如下:
```c++
#include <fstream>
using namespace std;
int main() {
double data[] = {1.23, 69.88, 34.45, 67.98, 2345.67};
ofstream out("data.bin", ios::out | ios::binary);
for (int i = 0; i < 5; i++) {
out.write(reinterpret_cast<const char*>(&data[i]), sizeof(double));
}
out.close();
return 0;
}
```
阅读全文