c++streamstringstreamostringstream

Convert std::ostringstream into std::stringstream


The next code returns an empty string in ss:

#include <string>       
#include <iostream>     
#include <sstream>      

int main () {
  std::ostringstream oss;
  oss << "Text";

  std::stringstream ss;
  ss.basic_ios<char>::rdbuf(oss.rdbuf());
  std::cout << ss.str() << "\n";
  return 0;
}

How can I return from ss the text introduced in oss? I'm mainly interested in converting std::ostringstream into std::stringstream.


Solution

  • Following comments from @NathanOliver, I decided to convert std::ostringstream into std::stringstream by using str():

    #include <string>       
    #include <iostream>     
    #include <sstream>      
    
    int main () {
      std::ostringstream oss;
      oss << "Text";
    
      std::stringstream ss;
      ss << oss.str();
      std::cout << ss.str() << "\n";
      return 0;
    }