Convert wchar_t * to UTF-16 string

I need C ++ code to convert the string specified in wchar_t*to a UTF-16 string. It should work on both Windows and Linux. During the search, I looked at many web pages, but the topic is still not clear to me.

As I understand it, I need:

  • Call setlocalewith LC_TYPE and UTF-16 encoding.
  • Use wcstombsto convert a string wchar_tto a UTF-16 string.
  • A call setlocaleto restore the previous locale.

Do you know how I can convert wchar_t*to UTF-16 in a portable way (Windows and Linux)?

+5
source share
5 answers

- ++ 03 ( ). , wchar_t . Windows wchar_t - 16- , - 32- . , .

+8

++ 11 std::codecvt_utf16 , .

std:: codecvt_utf16 - std:: codecvt, UTF-16 UCS2 UCS4 ( Elem).

: http://en.cppreference.com/w/cpp/locale/codecvt_utf16

+4

, wchar_t . GNU libiconv, , . "wchar_t" , . , Windows, Linux , libiconv.

+2

, wchar_t utf-32 , Windows. Linux Mac OS X * nix ( , , , : -)

wchar_t utf-16 Windows. Windows memcpy: -)

In all other respects, the conversion is algorithmic and fairly simple. Therefore, there is no need for fancy support from third-party libraries.

Here is the basic algorithm: http://unicode.org/faq/utf_bom.html#utf16-3

And you can find dozens of different implementations if you don't want to write your own :-)

+2
source

Does the g ++ compiler seem to support wcstombs?

-1
source

All Articles