Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 输出到字符串而不是wofstream_C++_String_Wstring_Wofstream - Fatal编程技术网

C++ 输出到字符串而不是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_

对于以下代码,是否可以将结果输出到字符串而不是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_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
不进行代码更改以生成正确的类型。