Overloading input operator >>

Hi everyone. I can't figure out what the bug in my code is. I have overloaded the input operator lots of times before, and I never had any problems.

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
#include <iostream>
#include <fstream>
#include <string>

class A { };

std::istream& operator>>(std::istream& is, A& arg)
{
	std::string s;
	int i;

	is >> s;
	if(!is) { std::cout << "error reading s" << '\n'; }
	is >> i;
	if(!is) { std::cout << "error reading i" << '\n'; }

	return is;
}

int main()
{
	A temp;
	std::ifstream ifs{"file.txt"};

	if(!ifs)
	{
		std::cout << "Could not open file" << '\n';
	}

	while(ifs >> temp)
	{
		if(!ifs)
		{
			std::cout << "bad input" << '\n';
			break;
		}
		else
		{
			std::cout << "good input" << '\n';
		}
	}

	std::cout << "Please enter a character to exit:" << '\n';
	std::cin.get();

	return 0;
}


file.txt
1
2
foo 1
bar 2


Console output:
1
2
3
4
good input
good input
error reading s // why does it keep reading the file
error reading i // even though it reached the end of the file? 


It shouldn't output error reading s and error reading i because it shouldn't continue calling the input operator.

Why does the input operator still get called even though ifs has reached the end of the file?

I tried to add a newline character at the end of the file, so file.txt looks like:
1
2
3
foo 1
bar 2


But I still get the same output.

Thanks in advance to anyone who replies!
Last edited on
Why does the input operator still get called even though ifs has reached the end of the file?

Because you continued to call it?

You execute your while loop at line 30 twice, each time outputing "good input".
Now you call your overload operator at line 30 for a third time. Eof has not been set yet. Line 12 sets eof. You output "error reading a". Now what do you do? You continue and attempt to read again. eof is still set. Line 14 fails. You output "error reading i" and fall through to your return.
@AbstractionAnon

Thank you so much for replying! Now I understand what happened and I just fixed my code.
1
2
3
4
5
6
7
8
9
while ( true )
{
    ifs >> temp;

    if ( ! ifs.good() )
      break;

    // do stuff with temp
}
Topic archived. No new replies allowed.