-1

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




Parviz Pirizade
  • 193
  • 2
  • 12

1 Answers1

1

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;
    }
Sourabh Burse
  • 359
  • 2
  • 7