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?
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.