Home > OS >  Writing to the stream buffer of a string stream overrides the previous data
Writing to the stream buffer of a string stream overrides the previous data

Time:12-05

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




CodePudding user response:

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;

CodePudding user response:

If you want to append the data in the beginning:

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