[英]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::sstringstream
, std::ostringstream
等转换为std::string
但未明确将std::ostream
为std::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引用实际上是一个
ostringstream
或stringstream
,请使用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
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. ostream
是ofstream
或iostream
,最有可能清除其缓冲区,所以你可能无法如上述提议提取全部内容。 Try this 尝试这个
std::ostringstream stream;
stream << "Some Text";
std::string str = stream.str();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.