Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

What I want to do is to create string stream , and output stream, giving the buffer of string stream to output stream, so that it will output data to the string stream. Everything seems fine, but when I try to add data to buffer of the string stream it overrides the previous data. My question is why? and how can achieve a result, such that it does not override but simply adds to the string stream. Here is my code below:

#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;
}




>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The reason that the string in the stringstream object is being overwritten when you write to it using the ostream object is that, by default, the ostream object writes to the beginning of the stream buffer. This means that when you write the string "hey" to the ostream object, it replaces the initial string in the stringstream object.

To fix this issue, you can use the ostream::seekp method to move the write position of the ostream object to the end of the stream buffer before writing to it. Here is an example of how you might do this:

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;

After making this change, the output of the program should be "hello I am string streamhey".

Alternatively, you can use the stringstream::str method to retrieve the current contents of the stringstream object as a string, and then append the new string to the end of this string. Here is an example of how you might do this:

stringstream s1("hello I am string stream");
string str = s1.str();
str += "hey\n";
s1.str(str);
cout <<s1.rdbuf()<<endl;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading