Search code examples
c++winapicharacter-encodingcharwchar-t

cp1251: encoding distortion when converting from char* to wchar_t*


I have a Russian string, stored in cpp source file with cp1251 encoding.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    const char *src = "Мой текст";
    wchar_t dst[30];

    switch (message)
    {
    case WM_CREATE:
        mbstowcs(dst, src, 29);
        //outputs "Ìîé òåêñò" instead of "Мой текст"
        MessageBox(hWnd, dst, L"Header", MB_OK);    
    ...

Unfortunately, "Мой текст" is distorted. Seems that mbstowcs shouldn't be used in this case, but what should I use?

Tried std::setlocale(LC_ALL, "ru_RU.cp1251"); at WinMain, but it didn't help.


Solution

  • According to Microsoft's documentation, the format of the locale string is language[_country_region[.code_page]] where code_page is the number of the code page without "cp". The table of supported languages and countries lists "Russian" and "Russia", so the correct string for setlocale is "Russian_Russia.1251".