Overloading extraction operator

Is there a reason why I can't reach my extraction for the istringstream stuff? It keeps looping before it even reaches the line : stuff >> year >> name >> percent >> sex;.. Think it has something to do with getline?

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
std::istream& operator >>(std::istream& input, BabyNames& x) {
	int count = 0;
	string line;
	while (!input.eof()) {

		getline(input, line);
		istringstream stuff(line);

		string name;
		int year;
		double percent;
		string sex;

		stuff >> year >> name >> percent >> sex;
		string boy = "boy";
		string girl = "girl";
		x.data[count].setYear(year);
		x.data[count].setName(name);
		x.data[count].setPercent(percent);
		count++;
		if (sex.compare(boy) == 0) {
			gender boy;
		}
		if (sex.compare(girl) == 0) {
			gender girl;
		}
		count++;
	}
}
I am not sure if this is the problem, but think about your code for a second. Suppose input has 1 line.

In your loop, you use getline to read that 1 line in input. The eof flag has not been set, because there is no way for the program to know that your file only had 1 line.

So after the loop, you test the loop condition again and it evaluates as true. This time, when you use getline, there is an error because there is no more lines to read in input. Now is when the eof flag is set.

However, the program is still trying to execute all the other commands in the loop, even though getline didn't actually get anything.
I think this has nothing to do with your question, but:
1. I don't understand lines 22 and 25.
2. You should return input.
Topic archived. No new replies allowed.