STL List insertion and retrieval?

Without getting too in depth, I’m reading lines from a file and creating the object “com” which I’m inserting into a list and trying to iterate back through it to print all the objects out. Either my problem is when I insert or retrieve but I’m not sure. It IS reporting that there are 4 entries (but they’re all the same object. When I output). Thanks again.

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
int cIdin;
	string cNamein, cPurposein;
	committeeClass com;
	list<committeeClass> committeelist;
	list<committeeClass>::iterator p = committeelist.begin();
	
	ifstream fil;
	fil.open("committee.txt");

	if( fil.fail() )
		cout << "File didn't open.";
	else
		cout << "Successfully entered file. " << endl;

	while (!fil.eof())
	{
		fil >> cIdin;
		com.setcId(cIdin);

		fil.ignore();
		getline(fil,cNamein);
		com.setcName(cNamein);

		getline(fil,cPurposein);
		com.setcPurpose(cPurposein);
		p = committeelist.insert(p, com);
	}
		fil.close();	

	//output iterator list
	for (p = committeelist.begin(); p != committeelist.end(); p++)
	{
		cout << *p;
	}   



The text file is as follows.

8234
Facilities Planning
Make decisions regarding future building expenses
8111
Faculty Senate
Advise the President of the university
5151
Student Counsel
Advise and support student leaders
1111
Sports and Recreation
Investigate funding


When it runs it outputs this…

1111
Sports and Recreation
Investigate funding
1111
Sports and Recreation
Investigate funding
1111
Sports and Recreation
Investigate funding
1111
Sports and Recreation
Investigate funding

Also, are lists global? Aka if I create one in a constructor can I use it in another member function?
1
2
3
4
5
6
7
8
committeeClass com;
...
while (!fil.eof())
{
...
p = committeelist.insert(p, com);
}
...


Inside your while loop, you keep on re-using the same variable "com". You should insert a copy of "com" object into the list so that at the end, the list can contain 4 different committeeClass objects in your case.
Topic archived. No new replies allowed.