Hi,
I have written a 2*3 matrix[1,2,3;4,5,6] to file. And then I tried to read the data back to initialize a 2D C++ vector.
The code is as following:
#include <cmath>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ofstream out_file;
ifstream in_file;
char *out_name = "test.bin";
out_file.open(out_name,ios::binary | ios::app);
short matrix[2][3] = {1,2,3,4,5,6};
// write matrix to a disk file.
for (int y=0; y<2; y++)
{
for (int x=0; x<3; x++)
{
out_file.write(reinterpret_cast<char*>(&matrix[y][x]),sizeof(short));
}
}
out_file.close();
cout<< "Matrix has been written to test.bin."<<endl;
vector< vector<short> >vec_2d;
vector<short>row;
in_file.open(out_name,ios::binary);
short m;
while(!in_file.eof())
{
for (int y=1; y<4; y++)
{
in_file.read(reinterpret_cast<char*>(&m),sizeof(short));
row.push_back(m);
if (y == 3)
{
vec_2d.push_back(row);
row.clear();
}
}
}
for (int i=0; i< vec_2d.size(); i++)
{
for (int j=0; j< vec_2d[i].size(); j++)
{
cout<<" "<<vec_2d[i][j];
}
cout<<endl;
}
in_file.close();
return 0;
}
However, the vector is printed out as [1,2,3;4,5,6;6,6,6]. I tried to fix it but in vain. Anybody can point out the mistake for me? Thank u in advance.
nanchuangyeyu