I\'ve been looking for a way to convert between the Unicode string types and came across this method. Not only do I not completely understand the method (there are no commen
I've written helper functions to convert to/from UTF8 strings (C++11):
#include
#include
#include
using namespace std;
template
string toUTF8(const basic_string, allocator>& source)
{
string result;
wstring_convert, T> convertor;
result = convertor.to_bytes(source);
return result;
}
template
void fromUTF8(const string& source, basic_string, allocator>& result)
{
wstring_convert, T> convertor;
result = convertor.from_bytes(source);
}
Usage example:
// Unicode <-> UTF8
{
wstring uStr = L"Unicode string";
string str = toUTF8(uStr);
wstring after;
fromUTF8(str, after);
assert(uStr == after);
}
// UTF16 <-> UTF8
{
u16string uStr;
uStr.push_back('A');
string str = toUTF8(uStr);
u16string after;
fromUTF8(str, after);
assert(uStr == after);
}