Converting std::wstring to utf-8 in C++ x11 and writing utf-8 files with fstream

Simple conversion can be done like this:

#include <string>
#include <codecvt>

std::string ws2utf8(std::wstring &input)
{
 std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8conv;
 return utf8conv.to_bytes(input);
}

std::wstring utf82ws(std::string &input)
{
 std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8conv;
 return utf8conv.from_bytes(input);
}

To write std::wstrings as utf8 text files:

#include <string>
#include <iostream>
#include <fstream>
#include <codecvt>

void writeUtf8(std::wstring output, std::string filename)
{
 std::ofstream utf8file(filename);
 std::wbuffer_convert<std::codecvt_utf8<wchar_t>> converter(utf8file.rdbuf());
 std::wostream out(&converter);

 out << output;

 utf8file.close();
}

Leave a Reply