我有以下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 64位
下运行Visual Studio 2013 Express for Desktop答案 0 :(得分:2)
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字符,更不用说'ä','ö','ü','ß','◄等字符','■'和'►'。
如果要获取用户计算机配置使用的语言环境,则可以使用空字符串作为名称。您还可以使用此区域设置填充流,而无需使用全局区域设置。
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.