首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >写入字符串流的流缓冲区将覆盖以前的数据。

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

Stack Overflow用户
提问于 2022-12-04 12:04:40
回答 2查看 35关注 0票数 -1

我想要做的是创建字符串流和输出流,将字符串流的缓冲区提供给输出流,以便将数据输出到字符串流。一切看起来都很好,但是当我试图向字符串流的缓冲区中添加数据时,它会覆盖以前的数据。我的问题是为什么?以及如何实现结果,这样它就不会覆盖而是简单地添加到字符串流中。下面是我的代码:

代码语言:javascript
复制
#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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-12-04 12:42:53

stringstream对象中的字符串在使用ostream对象写入它时被覆盖的原因是,默认情况下,ostream对象写入流缓冲区的开头。这意味着当您将字符串"hey“写入ostream对象时,它将替换stringstream对象中的初始字符串。

要解决此问题,可以使用ostream::seekp方法将ostream对象的写入位置移动到流缓冲区的末尾,然后再写入该对象。下面是您如何做到这一点的一个示例:

代码语言:javascript
复制
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的末尾。下面是您如何做到这一点的一个示例:

代码语言:javascript
复制
stringstream s1("hello I am string stream");
string str = s1.str();
str += "hey\n";
s1.str(str);
cout <<s1.rdbuf()<<endl;
票数 2
EN

Stack Overflow用户

发布于 2022-12-04 13:02:21

如果您想在开始时附加数据:

代码语言:javascript
复制
 #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;
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74675402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档