我想要做的是创建字符串流和输出流,将字符串流的缓冲区提供给输出流,以便将数据输出到字符串流。一切看起来都很好,但是当我试图向字符串流的缓冲区中添加数据时,它会覆盖以前的数据。我的问题是为什么?以及如何实现结果,这样它就不会覆盖而是简单地添加到字符串流中。下面是我的代码:
#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;
}发布于 2022-12-04 12:42:53
stringstream对象中的字符串在使用ostream对象写入它时被覆盖的原因是,默认情况下,ostream对象写入流缓冲区的开头。这意味着当您将字符串"hey“写入ostream对象时,它将替换stringstream对象中的初始字符串。
要解决此问题,可以使用ostream::seekp方法将ostream对象的写入位置移动到流缓冲区的末尾,然后再写入该对象。下面是您如何做到这一点的一个示例:
stringstream s1("hello I am string stream");
streambuf *s1_bfr = s1.rdbuf();
ostream my_stream (s1_bfr);
my_stream.seekp(0, ios_base::end); // move the write position to the end of the stream
my_stream <<"hey"<<endl;
cout <<s1.rdbuf()<<endl;在进行此更改后,程序的输出应该是"hello I I string“。
或者,您可以使用stringstream::str方法以string的形式检索stringstream对象的当前内容,然后将新字符串追加到该string的末尾。下面是您如何做到这一点的一个示例:
stringstream s1("hello I am string stream");
string str = s1.str();
str += "hey\n";
s1.str(str);
cout <<s1.rdbuf()<<endl;发布于 2022-12-04 13:02:21
如果您想在开始时附加数据:
#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;
}https://stackoverflow.com/questions/74675402
复制相似问题