0

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
2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by nanchuangyeyu
0

This: while(!in_file.eof()) will cause your last line in the file to be read twice. And thus your loop will be executed 1 time too many and you get one row extra with the last read value. (in your case 6).

0

Thank you for your help niek_e, then what should I do in order to obtain the desired result?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.