开发者

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

开发者 https://www.devze.com 2022-12-31 11:01 出处:网络
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

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;


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消