我在Windows控制台中输出unicode字符时遇到问题。 我使用Windows XP和代码块12.11与mingw32-g ++编译器。
使用C或C ++在Windows控制台中输出unicode字符的正确方法是什么?
这是我的C ++代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "šđč枊ĐČĆŽ" << endl; // doesn't work
string s = "šđč枊ĐČĆŽ";
cout << s << endl; // doesn't work
return 0;
}
提前致谢。 :)
答案 0 :(得分:7)
这些字符中的大多数都需要多个字节进行编码,但std::cout
当前所使用的区域设置只会输出ASCII字符。因此,您可能会在输出流中看到许多奇怪的符号或问号。您应该使用使用UTF-8的区域设置std::wcout
,因为ASCII不支持这些字符:
// <locale> is required for this code.
std::locale::global(std::locale("en_US.utf8"));
std::wcout.imbue(std::locale());
std::wstring s = L"šđč枊ĐČĆŽ";
std::wcout << s;
对于Windows系统,您需要以下代码:
#include <iostream>
#include <string>
#include <fcntl.h>
#include <io.h>
int main()
{
_setmode(_fileno(stdout), _O_WTEXT);
std::wstring s = L"šđč枊ĐČĆŽ";
std::wcout << s;
return 0;
}