Tuesday, March 21, 2017

C++: Convert Unicode String to ANSI String

I've seen so many examples and questions of how to convert between unicode string and ANSI string using C++. So here is by far the easiest way to do this conversion that I've implemented:

template <typename Facet>
struct TFacet : Facet
{
    using Facet::Facet;
};

wstring stringtowstring(string value)
{
    std::wstring_convert<TFacet<std::codecvt<wchar_t, char, std::mbstate_t>>> conv;
    return conv.from_bytes(value);
}

string wstringtostring(wstring value)
{
    std::wstring_convert<TFacet<std::codecvt<wchar_t, char, std::mbstate_t>>> conv;
    return conv.to_bytes(value);

}

No comments:

Post a Comment