C++ 输出到字符串而不是wofstream
对于以下代码,是否可以将结果输出到字符串而不是wofstream?谢谢你C++ 输出到字符串而不是wofstream,c++,string,wstring,wofstream,C++,String,Wstring,Wofstream,对于以下代码,是否可以将结果输出到字符串而不是wofstream?谢谢你 wstring w = L"test"; std::wofstream ofs("test.txt"); std::locale utf8_locale(std::locale(), new boost::archive::detail::utf8_codecvt_facet()); ofs.imbue(utf8_locale); std::copy(w.begin(),w.end(), std::ostream_
wstring w = L"test";
std::wofstream ofs("test.txt");
std::locale utf8_locale(std::locale(), new boost::archive::detail::utf8_codecvt_facet());
ofs.imbue(utf8_locale);
std::copy(w.begin(),w.end(),
std::ostream_iterator<wchar_t, wchar_t>(ofs));
wstring w=L“测试”;
std::wofstream ofs(“test.txt”);
std::locale utf8_locale(std::locale(),new boost::archive::detail::utf8_codecvt_facet());
ofs.imbue(utf8_地区);
std::copy(w.begin(),w.end(),
std::ostream_迭代器(ofs);
<代码> > P>输出字符串流是一种C++特性,其特性与输出文件流类似,因为它们都继承了从<代码> STD::OsStrase,这意味着在两者中可以使用相同的函数。但是,字符串流对字符串而不是文件进行操作
这意味着您需要做的就是(因为您没有使用任何wofstream
-特定函数)将ofs
的类型更改为字符串流:
#include <sstream>
std::wostringstream oss;
#包括
std::wostringstream-oss;
现在我无法获得locale stuff building(到目前为止我还没有使用它们),但是对它们进行注释确实产生了正确的结果()。正如您所看到的,您可以通过字符串流的str()
函数访问字符串。嗨,克里斯,您能用一些代码进一步解释一下吗?我不熟悉C++std::wofstream
是从与std::wofstream
相同的类派生的,因此仅替换使用的变量类型应该仍然与您使用的其他函数兼容。Stringstreams维护的是一个字符串而不是一个文件(通过str()
)访问),它应该满足您的需要。比如std::string output=woss.str();?抱歉再次提出这个愚蠢的问题,您如何知道wostringstream和WofsStream是从同一个类派生的?我现在明白了。这也很有帮助:对。但实际上str()返回的是wstring,而不是字符串。。。谢谢你的回答@echo,稍加窥探,您会发现std::ostringstream
和std::wostringstream
实际上是同一个基本类,但具有不同的模板参数。前者是char
,后者是wchar\u t
。函数返回一个std::basic_字符串,其中CharT
是模板参数。这基本上分别计算为具有完全相同代码的std::string
或std::wstring
。如果您希望整个混乱使用您自己的字符类型,您可以说std::basic_ostringstream
不进行代码更改以生成正确的类型。