Unicode not printing



我有以下c++代码

char* locale = setlocale(LC_ALL, "German"); // Get the CRT's current locale.
std::locale lollocale(locale);
setlocale(LC_ALL, locale); // Restore the CRT.
wcout.imbue(lollocale); // Now set the std::wcout to have the locale that we got from the CRT.
COORD cur = { 0, 0 };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cur);
wcout << L"Enemy " << this->enemyStrengthLeft << L"/" << this->enemyStrength << endl;
wcout << L"◄";
for (int i = 0; i < 20; i++) {
  if (i % 2 == 0)
    wcout << L"■";
  else
    wcout << L" ";
}
wcout << L"►" << endl;

当我执行它时,unicode字符不在cmd窗口中,我该如何修复它?

编辑

我使用Lucida Console作为字体。

编辑2

如果有帮助,我在Windows 7 Enterprise SP1 64bit下运行Visual Studio 2013 Express for Desktop

Windows不是很好地通过标准库支持Unicode。可以通过标准库将任意Unicode打印到控制台,但这不是很方便,而且我所知道的所有方法都有令人不快的副作用。

使用Windows API:

std::wstring s = L"◄ ■ ►";
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), s.c_str(), s.size(), nullptr, nullptr);

顺便说一句,您获取区域设置并恢复它的代码并没有按照您的想法执行,有一个更好的方法。

char* locale = setlocale(LC_ALL, "German"); // Get the CRT's current locale.
std::locale lollocale(locale);
setlocale(LC_ALL, locale); // Restore the CRT.

setlocale返回函数运行后生效的区域名称。你总是会得到德语区域设置的名称,全局区域设置不会恢复到原始值。如果你真的想获得当前设置的语言环境,那么你可以通过传递nullptr而不是语言环境名称来实现:

char const *locale = std::setlocale(LC_ALL, nullptr);

获取当前语言环境而不更改它。

但是你应该知道,除非在某个时候改变了区域设置,否则它将是"C"区域设置。C和c++程序总是在这个语言环境中启动。"C"语言环境不一定允许您使用基本源字符集以外的字符(该字符集甚至不包括所有ASCII字符,更不用说'ä'、'ö'、'ü'、'ß'、' euref '、'■'和'►'等字符了)。

如果您想获得用户机器配置使用的区域设置,那么您可以使用空字符串作为名称。你也可以用这个语言环境注入一个流,而不用担心全局语言环境。

cout.imbue(std::locale("")); // just imbue a stream
char const *locale = std::setlocale(LC_ALL, ""); // set global locale to user's preferred locale, and get the name of that locale.

最新更新