0

This code is workng properly for me:

std::wstring wmsg_text = L"キエオイウカクケコサシスセソタチツテア";
char buffer[100] = { 0 };
WideCharToMultiByte(CP_UTF8, 0, wmsg_text.data(), wmsg_text.size(), buffer, sizeof(buffer)-1, NULL, NULL);

I wonder the cross platform analog of this code. I look to std::wcstombs with std::codecvt_utf8, but can't guess how to use this by right way.

Ir S
  • 445
  • 1
  • 6
  • 19
  • 1
    For usage of `codecvt_utf8` have a look at http://stackoverflow.com/a/12903901/2131459 - but note that the comments say this approach was not working reliably! – Chris Dec 02 '15 at 10:28
  • Embedded unicode in the source file is not guaranteed to work, it depends on your compiler. – M.M Dec 02 '15 at 10:38

2 Answers2

0

You want to use std::wcsrtombs, something like:

std::wstring wmsg_text = L"キエオイウカクケコサシスセソタチツテア";
const wchar_t* wstr = wmsg_text.data();
std::mbstate_t state = std::mbstate_t();
int len = 1 + std::wcsrtombs(nullptr, &wstr, 0, &state);
std::vector<char> mbstr(len);
std::wcsrtombs(&mbstr[0], &wstr, mbstr.size(), &state);
char* buffer = mbstr.data();
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
0

This code is working properly, too:

std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
std::string u8str = conv.to_bytes(msg);
Ir S
  • 445
  • 1
  • 6
  • 19