奇怪的字符而不是在WinAPI中使用Unicode的国家字母

Strange characters instead national letters using Unicode in WinAPI

本文关键字:Unicode 国家 字符 WinAPI      更新时间:2023-10-16


我的程序从文件中读取文本并将其放入组合框中。
当文件包含带有英文字符的文本时,一切正常。
当它包含一些波兰字母时,它们会替换为奇怪的字符。
文件编码为 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()));

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

对不起,我的英语:)很差

默认情况下

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);
}