2d array infiling from text problem

hello guys i seriously need ur help....i made a code to take readings from text file for my matrix....the problem is when i output the pattern is all rong...e.g
my input:
1 2 3
3 4 5
2 4 5
expected output:
1 2 3 0 0 0
3 4 5 0 0 0
2 4 5 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
the output that am getting:
1 2 3 3 4 5
2 4 5 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
which is not how i infiled it...can some1 plz help me get the expected output not de one am getting.....thanx in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile("input.txt");
ofstream outfile ("output.txt");
int m1[6][6]={0};
int i=0, j=0;
for (i=0; i<6; i++)
{
	for (j=0; j<6; j++)
	{infile>>m1[i][j];


	outfile<<m1[i][j]<<" ";
	} outfile<<endl;
}


return 0;
}
for (j=0; j<6; j++)

change to for (j=0; j<3; j++)
okay so what if i have multiple input of a square matrix
well it really depends on what you are trying to achieve. If you wish to store the second matrix next to the first, in the array then you will have to offset your start and end positions like so.

1
2
for (j=3; j<6; j++)
	{infile>>m1[i][j];


You could then make the third one

1
2
3
4
5
6
7
8
9
for (i=3; i<6; i++)
{
	for (j=0; j<3; j++)
	{infile>>m1[i][j];


	outfile<<m1[i][j]<<" ";
	} outfile<<endl;
}


And the forth one

1
2
3
4
5
6
7
8
9
for (i=3; i<6; i++)
{
	for (j=3; j<6; j++)
	{infile>>m1[i][j];


	outfile<<m1[i][j]<<" ";
	} outfile<<endl;
}


To eliminate the redundancy of the for loops you could create a counter variable and either an if else block or a switch case block to set i and j respective to the required part of the array you intend to input.

A question you should ask yourself is do I require to have them all in the same array?



Last edited on
Topic archived. No new replies allowed.