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