Problem with reading in a file into a vector

So I need to read a file into these vectors. The file goes like this:
Basename Number of locations X1 Y1 X2 Y2 ...X2104 Y2104
kdkdsk 2104 32.012 50.393 59.302 58.392
So it needs to read the basename, number of locations, and then based on the number of locations, read each of those into a vector and eventually do some calculations based on that.

Right now it is only reading the first one. And I can't use istream.

Any help would be great.

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
  int main()
{
	vector<double> xCoord;
	vector<double> yCoord;
	vector<string> basename;
	vector<int> number;
	
	double distance;
	vector<double> average;
	double total = 0;
	int count = 0;
	string bname;
	int numberoflocations;
	double x,y;
	ifstream myReadFile;
	myReadFile.open("../universe.dat");			//Opening file

	if(!myReadFile)								//Checking if file opened
	{
		cout << "Error opening file\n";
		exit(1);
	}

	while (myReadFile >> bname >> numberoflocations)			//Reading contents of file into vectors
	{
		basename.push_back(bname);
		number.push_back(numberoflocations);
		cout << bname << " " << numberoflocations << " ";
	
		while(count<numberoflocations)
		{
			while(myReadFile >> x >> y)
			{
				xCoord.push_back(x);
				yCoord.push_back(y);
				
				//cout << x << " " << y << " ";
			}
			count++;
		}
	}
Lines 30-40: it will read everything it can into coords vectors (until it fails), then increases count. All subsequent loops will skip reading (as stream is in failed state) increases count. More: when count becomes equal to numberoflocation, line 24 condition fails because stream is still in failed state.

HowToFix:
1) Get rid of inner loop and rewrite middle one condition as follows:
while ((count < numberoflocations) && (myReadFile >> x >> y))
2) Do not forget forget to check stream state after and deal with it accordingly (fail after middle loop is probably should result in program termination, when fail and eof after outer loop is fine)
Last edited on
Topic archived. No new replies allowed.