将 std::ostringstream 转换为 std::stringstream

Convert std::ostringstream into std::stringstream

下一个代码returns 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;
}

我怎样才能return从ss文中引入oss?我主要感兴趣的是将 std::ostringstream 转换为 std::stringstream.

您可以使用受保护的 std::streambuf::swap 成员函数来交换流缓冲区的内容与另一个

要访问它,您需要派生 class:

#include <iostream>
#include <sstream>

struct swapper : std::streambuf {
    using std::streambuf::streambuf;
    void swap(std::streambuf& rhs) {         // public proxy for protected swap
        std::streambuf::swap(rhs);
    }
};

// casting
void swapbuf(std::ostream& a, std::ostream& b) {
    static_cast<swapper*>(a.rdbuf())->swap(*b.rdbuf());
}

int main () {
    std::ostringstream oss;
    oss << "Text";
    std::stringstream ss;
    swapbuf(oss, ss);

    std::cout << "ss:  " << ss.str() << "\n";   // prints Text
}

根据 @NathanOliver 的评论,我决定将 std::ostringstream 转换为 std::stringstream 通过使用 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;
}