Output unicode strings in Windows console app

后端 未结 11 962
花落未央
花落未央 2020-11-21 11:20

Hi I was trying to output unicode string to a console with iostreams and failed.

I found this: Using unicode font in c++ console app and this snippet work

11条回答
  •  一整个雨季
    2020-11-21 12:03

    First, sorry I probably don't have the fonts required so I cannot test it yet.

    Something looks a bit fishy here

    // the following is said to be working
    SetConsoleOutputCP(CP_UTF8); // output is in UTF8
    wchar_t s[] = L"èéøÞǽлљΣæča";
    int bufferSize = WideCharToMultiByte(CP_UTF8, 0, s, -1, NULL, 0, NULL, NULL);
    char* m = new char[bufferSize]; 
    WideCharToMultiByte(CP_UTF8, 0, s, -1, m, bufferSize, NULL, NULL);
    wprintf(L"%S", m); // <-- upper case %S in wprintf() is used for MultiByte/utf-8
                       //     lower case %s in wprintf() is used for WideChar
    printf("%s", m); // <-- does this work as well? try it to verify my assumption
    

    while

    // the following is said to have problem
    SetConsoleOutputCP(CP_UTF8);
    utf8_locale = locale(old_locale,
                         new boost::program_options::detail::utf8_codecvt_facet());
    wcout.imbue(utf8_locale);
    wcout << L"¡Hola!" << endl; // <-- you are passing wide char.
    // have you tried passing the multibyte equivalent by converting to utf8 first?
    int bufferSize = WideCharToMultiByte(CP_UTF8, 0, s, -1, NULL, 0, NULL, NULL);
    char* m = new char[bufferSize]; 
    WideCharToMultiByte(CP_UTF8, 0, s, -1, m, bufferSize, NULL, NULL);
    cout << m << endl;
    

    what about

    // without setting locale to UTF8, you pass WideChars
    wcout << L"¡Hola!" << endl;
    // set locale to UTF8 and use cout
    SetConsoleOutputCP(CP_UTF8);
    cout << utf8_encoded_by_converting_using_WideCharToMultiByte << endl;
    

提交回复
热议问题