Unicode 字符 Visual C++

Rob*_*iac 0 c++ unicode utf-8 character-encoding visual-studio-2010

我试图让我的程序使用 unicode 字符。我在 Windows 7 x32 机器上使用 Visual Studio 2010。

我想打印的是皇后符号(“\ ul2655”),但它不起作用。我已将我的解决方案设置为使用 unicode。

这是我的示例代码:

 #include <iostream>
 using namespace std;

 int main()
 {
    SetConsoleOutputCP(CP_UTF8);
    wcout << L"\u2655";

    return 0;
 }
Run Code Online (Sandbox Code Playgroud)

此外,我尝试了许多其他建议,但没有任何效果。(例如,更改cmd字体,应用chcp 65001,与SetConsoleOutputCP(CP_UTF8)等相同)。

问题是什么?我还是第一次遇到这样的情况。在 linux 上,它是不同的。

谢谢你。

Mat*_*lia 5

一旦我设法在控制台上打印棋子;这里涉及几个复杂性。

首先,您必须在 stdout 上启用 UTF-16 模式;此处此处均对此进行了描述,这与 Mehrdad 的解释完全相同。

#include <io.h>
#include <fcntl.h>

...

_setmode(_fileno(stdout), _O_U16TEXT);
Run Code Online (Sandbox Code Playgroud)

然后,即使输出正确到达控制台,在控制台上您可能会得到垃圾而不是预期的字符;这是因为,至少在我的机器(Windows 7)上,默认的控制台字体不支持棋子字形。

要解决此问题,您必须选择支持它们的不同 TrueType 字体,但要使这种字体可用,您必须经历一些麻烦;就个人而言,我发现 DejaVu Sans Mono 工作得很好。

所以,此时,您的代码应该可以工作,并且代码如下(我过去编写的用于测试此问题的示例):

#include <wchar.h>
#include <stdio.h>
#include <locale.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif

enum ChessPiecesT
{
    King,
    Queen,
    Rock,
    Bishop,
    Knight,
    Pawn,
};

enum PlayerT
{
    White=0x2654,   /* white king */
    Black=0x265a,   /* black king */
};

/* Provides the character for the piece */
wchar_t PieceChar(enum PlayerT Player, enum ChessPiecesT Piece)
{
    return (wchar_t)(Player + Piece);
}

/* First row of the chessboard (black) */
enum ChessPiecesT TopRow[]={Rock, Knight, Bishop, Queen, King, Bishop, Knight, Rock};

void PrintTopRow(enum PlayerT Player)
{
    int i;
    for(i=0; i<8; i++)
        putwchar(PieceChar(Player, TopRow[Player==Black?i: (7-i)]));
    putwchar(L'\n');
}

/* Prints the eight pawns */
void PrintPawns(enum PlayerT Player)
{
    wchar_t pawnChar=PieceChar(Player, Pawn);
    int i;
    for(i=0; i<8; i++)
        putwchar(pawnChar);
    putwchar(L'\n');
}

int main()
{
#ifdef _WIN32
    _setmode(_fileno(stdout), _O_U16TEXT);
#else
    setlocale(LC_CTYPE, "");
#endif
    PrintTopRow(Black);
    PrintPawns(Black);
    fputws(L"\n\n\n\n", stdout);
    PrintPawns(White);
    PrintTopRow(White);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在 Windows 和 Linux 上应该同样有效。

现在你仍然有一个问题:字形太小而没有任何意义:

控制台上的棋盘

这只能通过扩大控制台字体来解决,但是您会发现所有其他字符都太大而无法使用。因此,总而言之,最好的解决方法可能就是编写一个 GUI 应用程序。