user342231
user342231

Reputation: 539

Can someone explain to me why my output is this? And how would I correct my output?

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;

Upvotes: 1

Views: 109

Answers (2)

Maik Beckmann
Maik Beckmann

Reputation: 5733

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();

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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.

Upvotes: 0

Related Questions