简体   繁体   English

将std :: ostream转换为std :: string

[英]Convert std::ostream to std::string

Legacy code I maintain collects text into an std::ostream . 我维护的旧代码将文本收集到std::ostream I'd like to convert this to a std::string . 我想将它转换为std::string

I've found examples of converting std::sstringstream , std::ostringstream etc to std::string but not explicitly std::ostream to std::string . 我找到了将std::sstringstreamstd::ostringstream等转换为std::string但未明确将std::ostreamstd::string示例。

How can I do that? 我怎样才能做到这一点? (Ancient C++ 98 only, no boost please) (仅限古代C ++ 98,请不要提升)

  • If you have aa stringstream or a ostreamstring , object or reference, just use the ostringstream::str() method that does exactly what you want: extract a string . 如果你有一个stringstream或一个ostreamstring ,object或reference,只需使用完全符合你要求的ostringstream::str()方法:提取一个string But you know that and you apparently have a ostream object, not a stringstream nor a ostreamstring . 但你知道,你显然有一个ostream对象,而不是stringstream也不是ostreamstring

  • If your ostream reference is actually a ostringstream or a stringstream , use ostream::rdbuf to get a streambuf , then use this post to see how to extract a string . 如果您的ostream引用实际上是一个ostringstreamstringstream ,请使用ostream::rdbuf获取streambuf ,然后使用此帖子查看如何提取string

Example: 例:

#include <iostream>
#include <sstream>

std::string toString( std::ostream& str )
{
    std::ostringstream ss;
    ss << str.rdbuf();
    return ss.str();
}

int main() {

    std::stringstream str;
    str << "Hello";

    std::string converted = toString( str );

    std::cout << converted;

    return 0;
}

Live demo: http://cpp.sh/6z6c 现场演示: http//cpp.sh/6z6c

  • Finally, as commented by MM, if your ostream is a ofstream or an iostream , most likely it clears its buffer so you may not be able to extract the full content as proposed above. 最后,如MM评论,如果您ostreamofstreamiostream ,最有可能清除其缓冲区,所以你可能无法如上述提议提取全部内容。

Try this 尝试这个

 std::ostringstream stream;
 stream << "Some Text";
 std::string str =  stream.str();

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

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