Reading a data file into a 2 dimensional array?

Part of my assignment is to read from a data file using a 2 dimensional array (essentially we have to make a factory production type program that we can read/write too and a few other things). The problem I'm having is that when I try and run it the console just spits out 0's upon 0's.

The data file
1
2
3
4
5
6
7
300 450 500 210
510 600 750 400
627 100 420 430
530 621 730 530
200 050 058 200
100 082 920 290
 


and here's the part of the code.
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
28
29
30
31
32
33
34
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <fstream>
using namespace std;

const int fac = 6;
const int shift = 4;
int factory[fac][shift];

int main()
{
ifstream inFile("factory.txt", ios::in);
inFile.precision(2);
inFile.setf(ios::fixed, ios::showpoint);
inFile >> factory[0][0];

while (!inFile.eof())
	{
		for(int fac=0; fac<6; fac++)
		{
			for(int shift=0; shift<4; shift++)
			{
				cout<< factory[fac][shift] << " ";
			}
			cout <<"\n";
		}
		
	}

inFile.close();
return 0;
}


inFile >> factory[0][0]; read in the first digit of your file only. Then, you tried outputting the array, which, printed zeroes. I'm surprised, since it wasn't initialized, that it didn't spew out large numbers instead. Anyway, you first have to read the file into each array cell, like so..
1
2
3
4
5
6
7
8
9
10
while (!inFile.eof())
{
       for(int a=0; a<fac; a++) // Since fac is a const, you really can't use it in a for loop
	{
		for(int b=0; b<shift; b++)  //Since shift is a const, you really can't use it in a for loop
		{
			inFile >>  factory[a][b];
		}
	}
}


Now you can print it to screen.
Last edited on
Thank you for your help it works now and I have a better understanding how data files and arays work.

Now I just pray the next part I have to do works.
Last edited on
Topic archived. No new replies allowed.