C++ 11 helpers: char to wchar (& vice versa) easy conversions

Hello all,

i wanted to share two useful functions in order to convert between char & wchar strings in C++ 11. A colleague shared the info with me & i thought that may be interesting to share it with you guys. Thus, no more calls to mbtowc & wcstomb (da fuck name is this?) of stdlib & details about the max buffer size.

C++ 11 style char 2 wchar converters

#include <locale>
#include <codecvt>

std::wstring s2ws(const std::string& str)
{
       typedef std::codecvt_utf8<wchar_t> convert_typeX;
       std::wstring_convert<convert_typeX, wchar_t> converterX;

       return converterX.from_bytes(str);
}

std::string ws2s(const std::wstring& wstr)
{
       typedef std::codecvt_utf8<wchar_t> convert_typeX;
       std::wstring_convert<convert_typeX, wchar_t> converterX;

       return converterX.to_bytes(wstr);
}

For more info about the converters check the links below,

Kazeone

 

Links

wctomb Convert wide character to multibyte sequence

mbtowc Convert multibyte sequence to wide character

wstring_convert

codecvt_utf8

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s