【发布时间】:2018-07-30 22:30:37
【问题描述】:
我想用 fstream 写和读一个数组,发生了一些错误... 写过程的代码是:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
float a[4][16] = {
3.16216,
5.97973,
4.18243,
4.60135,
2.7027,
6.96622,
6.50676,
4.28378,
5.43919,
8.51352,
5.30405,
8.10135,
2.07432,
7.83784,
3.67568,
8,
5.25197,
8.83465,
6.35433,
6.65354,
5.01575,
7.32283,
6.95276,
4.50394,
4.77165,
8.18898,
5.43307,
7.65354,
4.64567,
8.03937,
4.48031,
7.49606,
4.13333,
6.8381,
4.94286,
5.09524,
3.19048,
6.48571,
9.17143,
4.78095,
4.24762,
8.30476,
8.22857,
7.33333,
3.27619,
9.38095,
2.56191,
7.44762,
4.05195,
6.94805,
5.12338,
5.35065,
3.43507,
6.71429,
8.48052,
3.94805,
5.88312,
8.27922,
7.34416,
7.81818,
2.79221,
8.90909,
4.25325,
7.26623 };
ofstream database("test.db");
for (int i = 0; i < 4; i++)
{
database.write((char *)a[i], sizeof(float) * 16);
}
database.close();
}
读取过程的代码为:
float a[4][16] = { 0 };
ifstream database("test.db");
for (int i = 0; i < 4; i++)
{
database.read((char *)a[i], sizeof(float) * 16);
for (int j = 0; j < 16; j++)
{
cout << "output: " << a[i][j] << endl;
}
}
发生了一些错误:
最后两个元素无法正确加载。但是,如果我更改数组的大小,例如,将 a[4][16] 更改为 a[4][15],一切都会好起来的。谁能给我一些建议,非常感谢!
【问题讨论】:
-
二维数组是连续的,所以你可以忘记循环,直接写
4 * 16items。 -
您可能遇到了 ASCII/二进制问题。使用
ostream::write和istream::read时,需要使用二进制方式打开文件。 -
非常感谢,二进制模式运行良好!
标签: c++ arrays ifstream ofstream