如何在 C/C++ 中输出 unicode 字符

2022-01-11 00:00:00 unicode windows c console c++

我在 Windows 控制台中输出 unicode 字符时遇到问题.我正在使用带有 mingw32-g++ 编译器的 Windows XP 和 Code Blocks 12.11.

I have problems with outputing unicode characters in Windows console. I am using Windows XP and Code Blocks 12.11 with mingw32-g++ compiler.

在 Windows 控制台中使用 C 或 C++ 输出 unicode 字符的正确方法是什么?

What is the proper way to output unicode characters in Windows console with C or C++?

这是我的 C++ 代码:

This is my C++ code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    cout << "??????????" << endl; // doesn't work

    string s = "??????????";
    cout << s << endl;            // doesn't work

    return 0;
}

提前致谢.:)

推荐答案

这些字符中的大多数需要超过一个字节来编码,但是 std::cout 目前的灌输语言环境将只输出 ASCII人物.出于这个原因,您可能会在输出流中看到很多奇怪的符号或问号.您应该为 std::wcout 注入使用 UTF-8 的语言环境,因为 ASCII 不支持这些字符:

Most of those characters take more than a byte to encode, but std::cout's currently imbued locale will only output ASCII characters. For that reason you're probably seeing a lot of weird symbols or question marks in the output stream. You should imbue std::wcout with a locale that uses UTF-8 since these characters are not supported by 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 系统,您将需要以下代码:

For Windows systems you will need the following code:

#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;
}

相关文章