Help required to load a text file into a vector matrix

Hi,

I need your help to design a program which can read text file and store in a vector matrix of integer type.

text file contains data like this

0 10
10 23 20
1 16 8 36
8 18 7 16
36 20 6
2 18 7
7 20 33
3 18 8
4 9 6
9 18 28
6 20 7
5 20 6
33 20 7 1
16 19 18 8
18 19 28 16
28 18 9 11

I can not specify the number of rows and columns.

Thanks in advance,
Last edited on
You might want to look at this link: http://www.cplusplus.com/doc/tutorial/files/

In addition, you'll be reading the data as strings, you can use the stringstream object to aid your conversion to the "int" data type you desire. link: http://www.cplusplus.com/reference/iostream/stringstream/stringstream/
Thank you for reply, Can anyone give me a program template?
Unless I am missing something, that sample data is pathological.
closed account (D80DSL3A)
This program works on your sample data. The methods may not be ideal though...
The test output echoes the file contents well.
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
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;

int main()
{
	vector<vector<int>> matVec;// 2d vector for storing all data read from file
	vector<int> lineVec;// for the entries on each line
	ifstream infile("dataIn.txt");
	if(infile)
	{
		int val = 0;
		while(!infile.eof())
		{
			infile >> val;
			lineVec.push_back(val);
			if( infile.peek() == '\n' )// last entry on the line has been read
			{
				matVec.push_back(lineVec);// push all of the lines entries at once
				lineVec.clear();// prepare to read the next line
			}			
		}
		infile.close();

		// output the matrix contents to test the file read
		for(size_t n=0; n<matVec.size(); ++n)
		{
			for(size_t k=0; k<matVec[n].size(); ++k)
				cout << matVec[n][k] << " ";
			cout << endl;
		}
	}
	else
		cout << "file was not opened." << endl;
	cout << endl;
	return 0;
}

EDIT: I just noticed that the last line doesn't get stored unless it ends with a newline so, make sure a newline appears at the end of the file or fix the program so it works regardless.
Last edited on
Thanks all it works
Topic archived. No new replies allowed.