Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wide to narrow characters

What is the cleanest way of converting a std::wstring into a std::string? I have used W2A et al macros in the past, but I have never liked them.

like image 367
DanDan Avatar asked Dec 09 '22 18:12

DanDan


2 Answers

What you might be looking for is icu, an open-source, cross-platform library for dealing with Unicode and legacy encodings amongst many other things.

like image 152
bmargulies Avatar answered Dec 18 '22 18:12

bmargulies


The most native way is std::ctype<wchar_t>::narrow(), but that does little more than std::copy as gishu suggested and you still need to manage your own buffers.

If you're not trying to perform any translation but just want a one-liner, you can do std::string my_string( my_wstring.begin(), my_wstring.end() ).

If you want actual encoding translation, you can use locales/codecvt or one of the libraries from another answer, but I'm guessing that's not what you're looking for.

like image 45
Potatoswatter Avatar answered Dec 18 '22 19:12

Potatoswatter