What does cin return?

I have just started reading a popular book by Skiena and was solving problems at the end of chapter 1. The description of input was:

INPUT
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0.

This has to be taken from stdin and not some file so how to check for EOF.

Can I use the following to check for end of input?

1
2
3
while(cin>>num1>>num2){
      // rest of code
}


Is this the right method? If not, then what is? And what does cin return?
<The online judge returned wrong answer and since the problem was trivial, I am expecting that problem lies here.>
> Can I use the following to check for end of input?
> while(cin>>num1>>num2) {

Yes; to check for input without an error.

cin >> num1 returns a reference to cin.

If cin >> num1 is able to read an int, cin continues to be in a good state;
if the attempt at input fails, cin is set to a state that is not good.

In if(cin), the condition is true if cin is in a good state.

This loop is canonical:
1
2
3
4
while( cin >> num1 >> num2 ) // as long as two numbers were successfully read
{
      // do something with those numbers
}
Can I use the following to check for end of input?

1
2
3
while(cin>>num1>>num2){
      // rest of code
}


Yes. It's not about what "cin returns", it about what it can become.

What happens in your while() is this:

1) The first operator>> extracts num1 from cin and returns (the modified) cin.
2) The second operator>> extracts num2 from cin and returns the (again modified) cin.
3) cin is converted to void* which gets converted to bool.

If there was an error or end-of-file was reached, cin will basically be converted to false, otherwise it will be true.

http://cplusplus.com/reference/ios/ios/operator_voidpt/
Topic archived. No new replies allowed.