Wondering what's going on here. I've tried to push this through gdb but can't seem to get a debug version / code of libstdc++, so hoping someone who knows their streams can help? In the code below, the key bit is the while loop:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <sstream>
using namespace std;
void printer(int i) {
cout << i << ", ";
}
int main ()
{
string s;
getline(cin, s);
stringstream input(s);
vector<int> v1;
int i;
while (!input.fail())
{
input >> i;
v1.push_back(i);
}
for_each(v1.begin(), v1.end(), printer);
return 0;
}
When I run this and supply a number, this appears to add that number twice to the vector. If I change the while loop's condition to eof()
(as opposed to fail()
) everything behaves as I'd have expected.
So given the extraction operator>>
is supposed to extract values from a stream, how is it possible that successive calls keep producing the result?
I'm guessing that I'm not thinking about this quite right (it's 2:30am localtime so that might have something to do with it!)
Using gcc version 4.9.2 (Ubuntu 4.9.2-0ubuntu1~12.04)