I wasn't totally clear what you wanted from the question, but I'm assuming you want to read in an n x n array from two different files, where n is not known until the file has been opened. The code below should do that.
Note the use of new
to declare an array of a size which is only known at run-time, and the slightly clumsy indexing i*n1 + j
etc. This is because the c++ standard (or at least the earlier ones) don't support Variable Length Arrays... it turns out they work fine on my compiler, but I understand there is no guarantee they will work on all compilers (see here). An alternative would be to use vectors rather than arrays.
Also there's a lot of repetition in this code so you'd probably be better of putting repeated stuff in a function.
/*
// mat1.txt
3
1 2 3
4 5 6
7 8 9
*/
/*
// mat2.txt
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
*/
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int n1, n2;
ifstream inFile1,inFile2;
inFile1.open ("mat1.txt");
inFile2.open ("mat2.txt");
inFile1 >> n1;
int* file1contents = new int[n1*n1];
for(int i=0; i<n1; ++i) {
for(int j=0; j<n1; ++j) {
inFile1 >> file1contents[i*n1 + j];
}
}
inFile2 >> n2;
int* file2contents = new int[n2*n2];
for(int i=0; i<n2; ++i) {
for(int j=0; j<n2; ++j) {
inFile2 >> file2contents[i*n2 + j];
}
}
// Print file contents to check it worked
cout << "File 1, size: " << n1 << ", contents:" << endl;
for(int i=0; i<n1; ++i) {
for(int j=0; j<n1; ++j) {
cout << file1contents[i*n1 + j] << ",";
}
cout << "\n";
}
cout << endl;
cout << "File 2, size: " << n2 << ", contents:" << endl;
for(int i=0; i<n2; ++i) {
for(int j=0; j<n2; ++j) {
cout << file2contents[i*n2 + j] << ",";
}
cout << "\n";
}
cout << endl;
delete [] file1contents;
delete [] file2contents;
inFile1.close();
inFile2.close();
return 0;
}