提问人:Parviz Pirizade 提问时间:12/4/2022 更新时间:12/4/2022 访问量:205
写入字符串流的流缓冲区会覆盖以前的数据
Writing to the stream buffer of a string stream overrides the previous data
问:
我想做的是创建字符串流和输出流,将字符串流的缓冲区提供给输出流,以便它将数据输出到字符串流。一切似乎都很好,但是当我尝试将数据添加到字符串流的缓冲区时,它会覆盖以前的数据。我的问题是为什么?以及如何实现结果,使其不会覆盖,而只是添加到字符串流中。这是我的代码如下:
#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;
}
答:
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;
}
评论
rdbuf
<<