I want to write a program so that it takes two sets of integer input from terminal and computes two sums. My intention is to separate the two sets of input by EOF (pressing Ctrl+D). Here is my code:
#include <iostream>
using namespace std;
int main(){
int i,sum=0;
while((cin>>i).good())
sum+=i;
cout<<"Sum 1 is "<<sum<<endl;
cin.clear();
sum=0;
while((cin>>i).good())
sum+=i;
cout<<"Sum 2 is "<<sum<<endl;
return EXIT_SUCCESS;
}
The compiled program worked fine for the first set of integer inputs. But as soon as I pressed Ctrl+D, the first sum was computed and printed and, without taking any further input, printed the second sum as 0. So basically the second while loop failed at the very beginning, even though cin.iostate had been set to good before it. So why did this happen? How should I change the program so that the second while loop would proceed as intended?