Alexandre Toqué
Alexandre Toqué

Reputation: 193

c++ cannot fill a stringstream anew

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;
}

Upvotes: 2

Views: 259

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490088

Although you'll still need to clear() the stream to write to it after you finish reading, you might consider using istream_iterators to read the data from the file:

stringstream ss1("0 1 2 3 40 5 6 76 8 9");

// initialize V from ss1
vector <int> V{std::istream_iterator<int>(ss1), std::istream_iterator<int>()};

// write values from V to ss2
std::copy(V.begin(), v.end(), std::ostream_iterator<int>(ss2));

ss1.clear();
ss1 << "helloooooo";

Upvotes: 0

youdontneedtothankme
youdontneedtothankme

Reputation: 672

Since you hit eof, the stream is in an error state. You have to reset it before you can use it again. In your case, I would drop the reset, and just use a fresh stringstream object.

Oh, and after ss1 >> number you should check the state of ss1 before using number. eof() doesn't return true before the last read failed

Upvotes: 0

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153810

First off, you should check if reading from the stream is successful by converting the stream to a Boolean value after you tried to read from it, e.g.:

while (ss1 >> number) {
    ...
}

Not testing after the input tends to result in processing the last input twice. Now, once this loop terminates, ss1 is in failure state, i.e., it has std::ios_base::failbit set. At this point the stream will refuse to do anything else until the bit is cleared. You can use clear() to reset the stream state:

ss1.clear();

After that the stream should be in good shape again.

Upvotes: 3

Related Questions