Reading a matrix from a file

Hello guys,
Firstly I want to apologize If I ask something silly, but I have just started learning C++, and I really don't know much.
As a practice I have a challenge of writing a matrix in a file, and then reading the information (numbers) from it, and in the end to be able to do some calculations, for example to multiply the positive members of that matrix.
So far I have only managed to write a matrix in a file by using this code:
-------
int main()
{
const int m=4, n=5;
int i,j;
int A[m][n]={{5,3,-4,8,2},
{1,5,2,7,-8},
{-3,9,5,2,4},
{4,-1,3,6,8}};
ofstream Write("c:/matrix/matrix.txt", ios::out);
for (i=0;i<m;i++)
{
For (j=0;j<n;j++)
Write << setw(3)
<< A[i][j] ;
Write << "n";
}
return 0;
}
--------------
Now the next thing i want to do, is to make some calculations with specific members of the matrix, say multiply the negative members or something like this.
I'm trying to use the "ifstream Read("c:/matrix/matrix.txt", ios::in)" to open the file for reading, but I can't figure it out how to achieve the above goal.
Can someone show me an example of how I might achieve this?

Thanks in advance for any kind of help.
Last edited on
closed account (S6k9GNh0)
Setup a text format and read the file using an algorithm to parse that format. Simple as that.
A common method is to write the size of the matrix, followed by the values. Typically you will see it formatted nicely, something like:
3 4
1 2 3 4
5 6 7 8
9 0 1 2
but it would be the very same if you stuck it all on one line:
3 4 1 2 3 4 5 6 7 8 9 0 1 2

The trick is to remember that the numbers have a specific order:

1 the first number is the number of rows
2 the second number is the number of columns
3 the next (m)(n) numbers are the values, stored in row major order, left to right and top to bottom.

Hence, your code to write a matrix is very much like what you have:

1
2
3
4
5
6
7
8
9
10
ofstream f("matrix.txt");
f << m << " " << n << "n";
for (int i = 0; i < m; i++)
  {
  for (int j = 0; j < n; j++)
    {
    f << A[i][j];
    }
  f << "n";
  }

The code to read a matrix is similar, except you must now account for the size of the matrix:

1
2
3
4
5
6
7
8
9
10
11
12
ifstream f("matrix.txt");
f >> m >> n;

if ((m != 4) || (n != 3))
  {
  cout << "Matrix not 4 by 3!n";
  return 1;
  }

for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
  f >> A[i][j];

Of course, if all your matrices are the same size, you can omit that information in the file.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.