简体   繁体   English

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

[英]Convert std::ostringstream into std::stringstream

The next code returns an empty string in ss:下一个代码在 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?如何从ss返回oss中引入的文字? I'm mainly interested in converting std::ostringstream into std::stringstream.我主要对将 std::ostringstream 转换为 std::stringstream 感兴趣。

You could make use of the protectedstd::streambuf::swap member function that exchanges the contents of the stream buffer with those of another您可以使用受保护的std::streambuf::swap成员 function 将 stream 缓冲区的内容与另一个缓冲区的内容交换

To get access to it, you'll need a derived class:要访问它,您需要派生的 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
}

Following comments from @NathanOliver , I decided to convert std::ostringstream into std::stringstream by using str() :根据@NathanOliver的评论,我决定使用str()std::ostringstream转换为std::stringstream

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM