我对 C++ 中的 WinAPI 编程还比较陌生。我正在尝试编写一个程序,该程序将使用 GetComputerName() 获取系统主机名。理想情况下,我希望代码能够在英语和非英语系统上工作。下面是我正在使用的代码:
int main()
{
wstring hostname;
wchar_t nbtName[MAX_COMPUTERNAME_LENGTH + 1];
DWORD length = MAX_COMPUTERNAME_LENGTH + 1;
GetComputerName(nbtName, &length);
hostname = nbtName;
wcout << hostname << endl;
return 0;
}
该代码在我的英文 Windows 7 系统上运行良好,但该代码似乎无法在我的德文 Windows 7 系统(使用德文字符作为主机名)上正确显示。我认为 wstring 和 wchar_t 可以处理这些特殊字符。这是我的德语 Windows 7 系统上显示的内容。
COMPUTER-Í─▄▀
我是不是忽略了一些愚蠢的事情?谢谢!
最佳答案
使用 _setmode(_fileno(stdout), _O_U16TEXT)
在控制台窗口中显示 Unicode:
#include <iostream>
#include <string>
#include <io.h> //for _setmode
#include <fcntl.h> //for _O_U16TEXT
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
std::wcout << L"ελληνικά\n";
return 0;
}
或使用 MessageBoxW(0, hostname.c_str(), 0, 0)
或 OutputDebugStringW
查看正确显示的 Unicode 文本:
关于c++ - GetComputerName() 未在 Windows 控制台中正确显示 Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36525395/