Interaction between cin, eofbit

Hello there,

I'm working on Stroustrups's Programming & Principles book and came up with a question I haven't been able to solve via Google.

Will cin ever flip the istream's EOF bit?

My guess is that it won't because cin doesn't read from a file (we use ifstream for that).

The question arose while writing a >> operator for a simple struct that holds two doubles. I use the >> operator to read from console and a file, so I needed to handle both situations. Reading from a file flips EOF correctly, but I'm not sure if cin will ever flip it and lead to a problem.

operator>>
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
istream& operator>>(istream& is, Point& p)
{
	char ch1 = '!', ch2 = '!', ch3 = '!';
	double xx = 0.0, yy = 0.0;

	if (!(is >> ch1 >> xx >> ch2 >> yy >> ch3))    // validate correct types
	{
		// note: error() from Stroustrup's header to throw exception
                if (is.bad()) error(">>(Point) bad istream"); // unrecoverable
		if (is.eof()) return is;	    // reached end of stream
		if (is.fail())	    // input didn't match
		{
			is.clear(ios_base::failbit);
			return is;
		}
	}

	if (ch1 != '(' || ch2 != ',' || ch3 != ')') // format error
	{
		is.clear(ios_base::failbit);
		return is;
	}

	p.x = xx;
	p.y = yy;
	return is;
}

Point struct
1
2
3
4
5
6
7
// simple (x,y) coordinate
struct Point
{
	Point() : x{ 0 }, y{ 0 } {};
	Point(double xx, double yy) : x{ xx }, y{ yy } {};
	double x, y;
};

The code compiles and runs fine for me. This is mostly a "what if" question. Thanks!
Last edited on
$ ./a.out < input
that's input redirection. Whenever in your program you read from the standard input stream (like cin), you'll be actually reading from the `input' file.
When `input' ends, cin would reach eof.


Also, read https://en.wikipedia.org/wiki/End-of-transmission_character
I did not know that. Thanks for the info ne555. Much appreciated.
Topic archived. No new replies allowed.