Why when i load data from a file last one is double.

What am I doing wrong. last data from file always double.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <vector>
#include <fstream>


struct Data {
	int apples;
	int oranges;
	
	void write(std::fstream &out) {
		out << apples << std::endl;
		out << oranges << std::endl;
	}
	
	void read(std::fstream &in) {
		in >> apples;
		in >> oranges;
	}
	
	void print() {
		std::cout << "Apples: " << apples << ",  ";
		std::cout << "Oranges: " << oranges << std::endl;
	}
};

Data push(int oranges, int apples) {
	Data temp;
	temp.apples = apples;
	temp.oranges = oranges;
	return temp;
}

void write() {
	std::vector<Data> data;
	data.push_back(push(11,5));
	data.push_back(push(4,7));
	data.push_back(push(9,10));
	
	std::fstream out("test.txt", std::ios::out);
	for(unsigned int i = 0; i < data.size(); i++)
		data[i].write(out);
	out.close();
}

int main() {
	std::vector<Data> data;
	Data temp;
	
	write();
	
	std::fstream in("test.txt", std::ios::in);
	while(!in.eof()) {
		temp.read(in);
		data.push_back(temp);
	}
	in.close();
	
	for(unsigned int i = 0; i < data.size(); i++)
		data[i].print();
	
	return 0;
}
My guess is this:
1
2
3
4
	while(!in.eof()) {
		temp.read(in);
		data.push_back(temp);
	}

You should not test for eof() in your while() clause. The reason being that EOF is not flagged until after the read fails. So if temp.read(in) fails (because you reached the end-of-file) you will still push it onto your std::vector<>

One way to fix this would be to change your function read() so that it returns true or false to signal if the read was successful. You can do that like this:
1
2
3
4
	bool read(std::fstream &in)
	{
		return (in >> apples >> oranges);
	}

Then you can make that the condition of your while() loop:
1
2
3
4
5
	while(temp.read(in))
	{
		// only do this if read() was successful
		data.push_back(temp);
	}

Hope that helps.
Thanks that works.
Topic archived. No new replies allowed.