views:

64

answers:

2

In this slice of code I get an output of

bbb 55 66 77 88
aaa

the output I expect and want is

bbb 55 66 77 88
bbb

because I reassign ss from log[0] to log[1]. So my question is why is the output different from what I expect and how do I change it to what I want?

      int w,x,y,z;
      stringstream ss (stringstream::in | stringstream::out);
      string word;
      string log[2];
      log[0]="aaa 11 22 33 44";
      log[1]="bbb 55 66 77 88";

      ss<<log[0];
      ss>>word;

      int k=0;
      ss>>w>>x>>y>>z;
      k++;

      ss<<log[k];
      cout<<log[k]<<endl;
      ss>>word;
      cout<<word<<endl;
      return 0;
A: 

When you write to the stringstream the second time the input pointer (tellg) is set to -1 and the fail bit is set. That means neither the second write nor the second read succeed.

Matthew Flaschen
can I do anything that would make that not occur?
cout<<log[k]<<endl; is successful, so why notcout<<word<<endl;
Why do you overwrite word before using the original value?
Matthew Flaschen
this is not my full code, just a slice that is causing the error, I do intend to rewrite, do something, rewrite, do something in a loop, so is it possible to reuse the "word"
+1  A: 

When

ss >> w >> x >> y >> z;

was executed, there is no content left to operate on and ss.good() returns false, which expresses the need to call ss.clear() in order to assure everything is ok and we can move on.

However, given that you do

ss.clear();
ss<<log[k];

The content of ss will be

aaa 11 22 33 44bbb 55 66 77 88

If you want it this way, fine. But maybe you expected it to contain

bbb 55 66 77 88

which is done by

ss.str(log[k]);
ss.clear();
Maik Beckmann
thank you, this explains alot