If your file contains
<matrix>
rows = 2
cols = 2
1 2
2 4
</matrix> |
then you need to write code that deals with the
<matrix>
rows = 2
cols = 2 |
part, because that's the first thing that's going to get read when you read the file.
Aside from that, on line 11, you never declared
inFile, and you don't need the curly braces on lines 12 and 24.
Also, on line 20,
inFile >> ar[a][b] >> endl;
is an error since
endl is only for output streams.
You also don't need to
#include <cstring>
, and you can just declare
a and
b in the
for
loop.
This code works for me with your given text file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
//#include <cstring> // Not needed
#include <fstream>
using namespace std;
int main()
{
int ar[2][2];
ifstream inFile("abc.txt");
for (int i = 0; i < 4; ++i)
inFile.ignore(1000, '\n'); // Eh, whatever (don't actually do this)
if (!inFile)
cout << "File not found!" << endl;
else
for (int a = 0; a < 2; a++)
{
for (int b = 0; b < 2; b++)
{
inFile >> ar[a][b];
cout << "Matrix is:" << ar[a][b] << endl;
}
}
//system("pause");
return 0;
}
|
Matrix is:1
Matrix is:2
Matrix is:2
Matrix is:4 |
But if you're thinking of copy-pasting it, don't, because all I did was make it throw out the first four lines of the text file, which is obviously not what you want since those lines contain valuable information about the size of the matrix.