data files

Hey Guys i need your input here..
I created a data file example.dat which looks like:

34 12 14
23 23 54
2 32 67
1 56 7
12 2 67

Then i created a program that extracts the data from the example.dat file and prints in the output as a matrix.. I wrote a program for that and all i get in an endless loop of 67 over and over again
Here is my program 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

#include <iostream>
using std::cerr;
using std::cout;
using std::endl;

#include <fstream>
using std::ifstream;

#include <cstdlib> // for exit function

int i, j,A[5][3];

int main()
{
	ifstream indata; // indata is like cin
	int num; // variable for input value
	
	indata.open("example.dat"); // opens the file
	if(!indata) { // file couldn't be opened
		cerr << "Error: file could not be opened" << endl;
		exit(1);
	}
	
	indata >> num;
 	i= 1;j=1;
	while ( !indata.eof() ) { // keep reading until end-of-file
		
		indata >> num; // sets EOF flag if no value found
		
		for (i=1; i<=3; i++) {
			for (j=1; j<=5; j++) {
				A[i][j]=num;
			}
		}
		
		
	}
	indata.close();
	cout << "End-of-file reached.." << endl;
	for (i=1 ;i=3; i++)
	{
		for (j=1;j=3; j++)
		{cout <<A[i][j]<<"   ";}
		cout <<endl;};
	
	return 0;
}




Any Inputs are highly appreciated!

Last edited on
Since the input file is tightly structured, you could loop through the rows of the matrix and read into the cells directly using something similar to:

indata >> A[i][0] >> A[i][1] >> A[i][2];

Where i is your loop variable bounded by the number of rows in your matrix.

I wanted in A[i][j] because later i want to work with bigger matrix depending on the situation.
Thanks!
Last edited on
Here:

1
2
3
4
5
6
7
8
9
	for (i=1 ;i=3; i++)
	{
		for (j=1;j=3; j++)
		{
                       cout <<A[i][j]<<"   ";
                }
		cout <<endl;
        };
 


the for loop is structured:

for( initialization; condition; increment)

you're setting i = 1 in the initialization, then setting i = 3 in the conditional and doing the same for the j loop. So it's printing out:

34 12 14
23 23 54
2 32 67 <---- this last column value.
1 56 7
12 2 67

for each printing.

Sorry, I didn't read your original post all the way through. I think I ate something spoiled and have been taking frequent emergency leaves from the keyboard.
Last edited on
Topic archived. No new replies allowed.