reading in from file into constructor

Ok I have a .txt that i need to read in. Each line of the .txt is formatted like

1 1 0 2 5
9 3 1 5 4
2 6 2 1 8

Each of these numbers are specific attributes. As I read in each line i need to assign each number to a specific attribute in a constructor. Any hints on how to make this constructor?

Thanks
Hi!

So, do you want to write a class, which has a constructor? If you want to store so many numbers I suggest to make an array in your class. Like this


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 <iostream>
#include <fstream>
using namespace std;

class myClass
{
	private:
	int array[3][5];
	public:
	myClass();
};

myClass::myClass()
{
	ifstream myfile;
	myfile.open("data.txt");
	if (!myfile.fail())
	{
		for (int r = 0; (r < 3) && (!myfile.eof()); r++)
			for (int c = 0; (c < 5) && (!myfile.eof()); c++) myfile >> array[r][c];
		myfile.close();
	}

	// only for checking
	for (int r = 0; (r < 3) ; r++)
	{
		for (int c = 0; (c < 5) ; c++) cout << array[r][c] << " ";
		cout << endl;
	}

}


int main()
{
	myClass m;
	return 0;
}
Is not a good idea having the file I/O in the class constructor.
I suggest you reading everything in a container ( eg: deque http://www.cplusplus.com/reference/stl/deque/ ) and then passing it to the constructor
@Bazzy:
Why it isn't good idea? (It worked properly for me.) If you have to read the settings from an ini file? Where do you want to put the reading when starting the program ?
It works but the file may be renamed/changed in format or such things. If you really want to read it from within the constructor, you should at least pass the file name as argument.
A container will allow you holding a variable amount of numbers.
:) I thought the ifstream musn't be used during of execution of constructor.
Topic archived. No new replies allowed.