Two arrays into one text file

Hey everyone

I have a 4*4 array and a 8*8 arays in my c++ program and i would like to save those arrays in one textfile. How do i do that.
If it is a binary file (a file for storing raw data), at the beginning of the file you can store 2 uint16_t values (aka unsigned short) that define the dimensions of the array. Then preform a loop that extracts data from the file. The amount of data after the 2 uint16_t values should be equivalent to the 2 uint16_t values multiplied together.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
using namespace std;

int main(){
	int a[4][4] = {0};
//	int b[8][8] = {1};
	
	ofstream os("a.dat", ios::out | ios::binary);
	os.write(reinterpret_cast<char*>(a),(4*4*sizeof(int)));
	os.close();

	int x[4][4];
	ifstream is("a.dat", ios::in | ios::binary);
	is.read(reinterpret_cast<char*>(x),(4*4*sizeof(int))); //Try commenting this line

	//print array x.
	for (int i = 0; i<4; i++){
		for (int j = 0; j<4; j++)
			cout << x[i][j] << ' ';
		cout << endl;
	}
	return 0;
}
i would like to save those arrays in one textfile.


Well, I assume you know how to store a single number in a text file?

You could write a function which first writes the the dimension, and then writes out the data row by row.

To make it human friendly, I'd probably write the dimension on one row and then the values for each matrix row on one row of the file.

2 2
1 0
0 1
3 3
0 1 0
1 0 1
0 1 0


Andy
We have defined a nxn matrix: A4 with n4=4, and a nxn matrix: A8 with n8=8.

We have tried this, but it doesn't work:

void UdskrivMatrixA48Fil(double A4[nmax][nmax],double A8[nmax][nmax], int n4,int n8)

{
int i,k;
ofstream UdFil;

UdFil.open("OrtMat48.txt");



for(i=0;i<n4;i++)
{
for(k=0;k<n4;k++)
{
UdFil<<A4[i][k]<<"\t";
}
UdFil<<"\n";
}


for(i=0;i<n8;i++)
{
for(k=0;k<n8;k++)
{
UdFil<<A8[i][k]<<"\t";
}
UdFil<<"\n";
}
UdFil.close();
}


This is what we get to the text file:
--------------------------------------------------

-858993460
8
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 11 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

----------------------------------------------------

We asume that the constant above the 8x8 matrix is supposed to be the A4 matrix, which doesn't work for some reason. Do you have an answer to this problem?
Sorry, this is what we have done:

void UdskrivMatrixA48Fil(double A4[nmax][nmax],double A8[nmax][nmax], int n4,int n8)
{
int i,k;
ofstream UdFil;

UdFil.open("OrtMat48.txt");

UdFil<<n4<<"\n";

for(i=0;i<n4;i++)
{
for(k=0;k<n4;k++)
{
UdFil<<A4[i][k]<<"\t";
}
UdFil<<"\n";
}

UdFil<<n8<<"\n";

for(i=0;i<n8;i++)
{
for(k=0;k<n8;k++)
{
UdFil<<A8[i][k]<<"\t";
}
UdFil<<"\n";
}
UdFil.close();
}
Topic archived. No new replies allowed.