read file into matrix

I need to read two matrices (A&B) from a file, do calculations, and output the result (C) into a new file. I do not know beforehand the size of the matrices, but most likely something small. I am having trouble with reading the data into two separate matrices. With what I have, I get a single column of 6 rows of the underflow(?) number.
data from file is in the format:
1 1 1
1 1 1
1 1 1

1 1 1
1 1 1
1 1 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
	for (i = 1; i <= size; i++)
	{
		for (j = 1; j <= size; j++)
		inFile >> matrixA [i][j];
		cout << matrixA[i][j];
	}

	for (k = 1; k <= size; k++)
	{
		for (l = 1; l <= size; l++)
		inFile >> matrixB[k][l];
		cout << matrixB[k][l];
	}
	
	outFile.open ("matrixC.txt");
	
	for (p = 1; p <= size; p++)
	{
		for (q = 1; q <= size; q++)
		outFile << matrixC[p][q];
		cout << matrixC[p][q];
	}

The cout in the loops is for me to see what's happening and is not necessary. I'd appreciate if someone could tell me what I've done wrong for it not to read in like I want.
Last edited on
Welcome! Read this:
http://cplusplus.com/forum/beginner/1/

also, enclose your code in [ code ] [ /code ] tags.

The first question you have to ask yourself when reading from a file is in what format the data is saved in the file. We'd need that information to help you. And please don't post your entire program here, most of that (if not all) is completely irrelevant to the question.
Thanks for responding so quickly. Is it better now?
Yes, it certainly is. Use getline to read the lines into strings until you hit an empty line. Then, you tokenize the lines to figure out how many columns you have. Then you check if the number of columns is the same in all lines you read, and then, and only then, you create a n*m matrix and read values into it, probably with a stringstream or something the like.

This is not the only way to do it, but that's what first came to my mind.
Thank you for your advice. If you're curious...

I was hesitant to use strings because I have to do calculations with the integers. But I eventually got around to this:
1
2
inFile >> element;
matrixB[k][l] = element;

inside the double for loop, which was inside a while loop.

Biggest problem after that was when, at some point, I changed j++ and l++ both to size++. Made an infinite loop. Took me hours to figure that one out.
Topic archived. No new replies allowed.