I emptied a stringstream, then I tried to fill it again without any success. II don't understand why. Here is my code:
#include <string> #include <iostream> #include <sstream> using namespace std; int main(int argc, char* argv[] ) { stringstream ss1, ss2; ss1 << "0 1 2 3 40 5 6 76 8 9"; // Stream is filled with one string of chars vector <int> V; string st; int number; while(!ss1.eof() ) { ss1 >> number; // Next int found in ss1 is passed to number V.push_back(number); ss2 << number << " "; // ss2 is filled with number + space in each iteration. } // Basically here, the content of ss1 has been passed to ss2, leaving ss1 empty. ss1 << "helloooo"; getline(ss1, st); cout << st << endl; // <--- Here, st appears to be empty... Why ? return 0; }
while (!eof())is really buggy. Usewhile (ss1 >> number).eof()is that it may never be reached, e.g., when you add a non-digit into your string: the stream will go into failure mode (i.e.,std::ios_base::failbitgets set) but unless you get over that, it won't ever reach EOF (i.e.,std::ios_base::eofbitwill never be set). More importantly, you need to check your stream after you tried to read because the stream doesn't know what you are going to attempt.