Pregunta

For the following code, is it possible to output the result to a string instead of wofstream? Thanks you!

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));
¿Fue útil?

Solución

Output string streams are a C++ feature that behave similarly to output file streams in the sense that they both inherit from std::ostream, meaning that you can use mostly the same functions in both. However, string streams operate on a string rather than a file.

What this means for you is that all you need to do (as you haven't used any wofstream-specific functions) is change the type of ofs to a string stream:

#include <sstream>
std::wostringstream oss;

Now I couldn't get the locale stuff building (I haven't used those as of yet), but commenting them did indeed produce correct results (see this test). As you can see, you can access the string via the string stream's str() function.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top