写入字符串流的流缓冲区会覆盖以前的数据

Writing to the stream buffer of a string stream overrides the previous data

提问人:Parviz Pirizade 提问时间:12/4/2022 更新时间:12/4/2022 访问量:205

问:

我想做的是创建字符串流和输出流,将字符串流的缓冲区提供给输出流,以便它将数据输出到字符串流。一切似乎都很好,但是当我尝试将数据添加到字符串流的缓冲区时,它会覆盖以前的数据。我的问题是为什么?以及如何实现结果,使其不会覆盖,而只是添加到字符串流中。这是我的代码如下:

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;

 int main ()
{

 stringstream s1("hello I am string stream");
 streambuf *s1_bfr =  s1.rdbuf();
 ostream my_stream (s1_bfr);
 my_stream <<"hey"<<endl;
 cout <<s1.rdbuf()<<endl; //gives the result  : " hey o I am string stream"( seems to me overriden)


return 0;
}




C++ stringstream ostream streambuf

评论

0赞 463035818_is_not_an_ai 12/4/2022
你为什么要这样使用 StringStream?为什么?为什么不干脆进入stirngstream呢?rdbuf<<
0赞 Parviz Pirizade 12/4/2022
因为我想用缓冲区来做,我不明白为什么它不起作用。
0赞 Sourabh Burse 12/4/2022
您想要的输出是什么?
0赞 Parviz Pirizade 12/4/2022
嘿你好我是字符串流

答:

1赞 Sourabh Burse 12/4/2022 #1

如果要在开头附加数据:

 #include <iostream>
 #include <iomanip>
 #include <string>
 #include <sstream>
    
    using namespace std;
    
    int main() {
        stringstream s1("hello I am string stream");
        streambuf *s1_bfr =  s1.rdbuf();
        stringstream temp; //Create a temp stringsteam
        temp << "hey"; //add desired string into the stream
        temp << s1_bfr; //then add your orignal stream
        s1 = move(temp); // or ss.swap(temp); 
        cout <<s1_bfr<<endl;
    
        return 0;
    }