c++ - 在 WinAPI 中使用 Unicode 替换奇怪字符而不是国家字母

标签 c++ winapi unicode


我的程序从文件中读取文本并将其放入组合框中。
当文件包含带有英文字符的文本时,一切正常。
当它包含一些波兰字母时,它们会被奇怪的字符替换。
文件编码为UTF-8(无BOM)。

myCombo = CreateWindowExW(WS_EX_CLIENTEDGE, (LPCWSTR)L"COMBOBOX", NULL,
                             WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST,
                             a, b, c, d,
                             hwnd, (HMENU)ID_COMBO, hThisInstance, NULL);

wstring foo;
wifstream bar("theTextFile.txt");
getline(bar, foo);
SendMessageW(myCombo, CB_ADDSTRING, (WPARAM)0, (LPARAM)(foo.c_str()));

我该怎么做才能让我的程序显示正确的国家字母?

PS。抱歉我的英语不好:)

最佳答案

默认情况下,

wifstream 不会在 Windows 上读取 UTF-8 文本。流区域设置中的 codecvt 方面是将文件中的字节转换为 wchar_t 的,因此您需要对其进行设置,以便它将转换为 wchar_t 你想要的。

类似这样的事情:

#include <fstream>
#include <string>

#include <locale>  // std::locale
#include <codecvt> // std::codecvt_utf8_utf16
#include <memory>  // std::unique_ptr

#include <Windows.h> // WriteConsoleW

int main(int argc, const char * argv[])
{
    std::wstring foo;
    std::wifstream bar("theTextFile.txt");

    typedef std::codecvt_utf8_utf16<wchar_t, 0x10FFFF, std::consume_header> codecvt;
    std::unique_ptr<codecvt> ptr(new codecvt);
    std::locale utf8_locale((std::locale()), ptr.get());
    ptr.release();
    bar.imbue(utf8_locale);

    std::getline(bar, foo);

    DWORD n;
    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), foo.c_str(), foo.size(), &n, NULL);
}

关于c++ - 在 WinAPI 中使用 Unicode 替换奇怪字符而不是国家字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824363/

相关文章:

python - ANSI、ASCII、Unicode 和与 Python 的编码混淆

c++ - 迭代 std::vector 的面向对象的方法?

c++ - 如何在 mshtml 中捕获应用程序崩溃或退出?

python - 如何在 Python 中将 unicode 字符串加载到 json 中?

c - WM_CHAR 不适用于 notepad.exe

c++ - 什么是 UpdatePerUserSystemParameters?

firefox - 为什么firefox没有utf-8编码?

c++ - OpenCV 矩阵比较器不起作用?

c++ - 简单的 Windows C++ 不可见

c++ - 如何将实际的 sf::Sprite 对象保存在数组或 vector 中? C++