Hey guys!
I must have some sort of logic problem that I'm just not seeing. I just want to read a file into a 2D array. The dimensions of the array are given by the very first line of the input file. Everything works hunky dorey except that when I print out the contents of my 2D array, I've got some extra zeroes at the end.
Here's the code:
#include <iostream>
#include <fstream>
#include <cassert>
using namespace std;
int main()
{
ifstream infile; //declare a file variable
int dim;
infile.open("input.dat"); //open a file
assert(infile); //make sure file opened
infile>>dim;
int matrix[dim][dim];
for(int row=0;row<dim;row++)
{
for(int col=0;col<dim;col++)
{
matrix[row][col]=0;
}
}
while(infile)
{
for (int row=0;row<dim;row++)
{
for (int col=0;col<dim;col++)
{
infile>>matrix[row][col];
}
}
infile.close();
}
//print 2D array
for(int row=0;row<dim;row++)
{
for(int col=0;col<dim;col++)
{
cout<<matrix[row][col];
cout<<endl;
}
}
system("pause");
return 0;
}
Here's my output:
123
456
789
0
0
0
0
0
0
Those zeroes at the end shouldn't be there. It's been awhile since I worked with arrays so I must be overlooking something...
This is what is in my input file:
3
123
456
789
Thanks for any help!