I'm using the following two different snippets of code to take the input of multiple numbers from the same line:
Snippet1:
int input {0};
while(cin >> input){
cout << "Read: " << input << endl;
if(cin.eof())
break;
}
Snippet2:
int input {0};
string str {NULL};
getline(cin, str);
istringstream ss {str};
while(ss >> input ){
cout << "Read: " << input << endl;
if(ss.eof())
break;
}
Input I'm using:
1 2 3 4 5
Output:
Read: 1
Read: 2
Read: 3
Read: 4
Read: 5
In both the codes I am able to read the numbers from the input, however in snippet 1 the loop doesn't exit even after printing all the numbers. Which means that cin.eof() doesn't return true even after there's nothing to be read from the input stream and thus the loop goes on. This problem however is not arising when I'm using istringstream - the loop terminates after printing the numbers. Can anyone explain why is this so? Both are text streams right? So why the difference in behaviour?