Windows 8 x64;
Visual Studio 2012;
我通过书本学习C++。在这个论坛上,我找到了有关通过C++读写Unicode字符串的many themes。但是此主题未标记为Solved(???)。在C++中,这真的是一个大问题吗?我尝试了不同的变体-它们对我不起作用:
#include<iostream>
#include<Windows.h>
#include <io.h>
#include <fcntl.h>
using namespace std;
int main() {
// variant 1:
wcout << L"Hello World!" << endl; // displayed
wcout << L"Привет Мир!" << endl;// not displayed
//**********************************************
// variant 2:
SetConsoleOutputCP(CP_UTF8);
wchar_t s[] = L"Hello World (2)!";
int bufferSize = WideCharToMultiByte(CP_UTF8, 0,
s, -1, NULL, 0, NULL, NULL);
char* m = new char[bufferSize];
WideCharToMultiByte(CP_UTF8, 0, s, -1, m,
bufferSize, NULL, NULL);
wprintf(L"%S", m); // valid output
wcout << endl;
printf("%s", m); // valid output
wcout << endl;
wchar_t s2[] = L"Привет мир (2)!";
int bufferSize2 = WideCharToMultiByte(CP_UTF8, 0,
s2, -1, NULL, 0, NULL, NULL);
char* m2 = new char[bufferSize2];
WideCharToMultiByte(CP_UTF8, 0, s2, -1, m2,
bufferSize2, NULL, NULL);
wprintf(L"%S", m2); // invalid output
wcout << endl;
printf("%s", m2); // invalid output
wcout << endl;
//**********************************************
// variant 3 (not working):
_setmode(_fileno(stdout), _O_U16TEXT);
wcout << L"Testing unicode -- English -- Ελληνικά"
<< "-- Español." << endl;
return 0;
}
但这仅适用于英语字符...
屏幕:
如何通过C++解决问题?
最佳答案
解决方法正在执行
在执行程序之前使用cmd.exe
(我不知道如何以编程方式执行此操作)。 65001是用于UTF8编码的不可思议的值。可用于chcp
的其他代码页列表在这里:http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/chcp.mspx?mfr=true。另一个有趣的值是Cyrillic CP1251的855。
并且不要忘记将控制台字体切换为Lucida(默认字体不适用于UTf-8)。