【问题标题】:Unicode character Visual C++Unicode 字符 Visual C++
【发布时间】:2013-11-02 03:23:30
【问题描述】:

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

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

这是我的示例代码:

 #include <iostream>
 using namespace std;

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

    return 0;
 }

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

有什么问题?这是我第一次遇到这样的情况。在 linux 上就不同了。

谢谢。

【问题讨论】:

标签: c++ visual-studio-2010 unicode utf-8 character-encoding


【解决方案1】:

Try this instead

_setmode(_fileno(stdout), _O_U16TEXT);

【讨论】:

  • 它没有用。它向我展示了带有 ASCII 219 代码的符号。
  • @RobertEagle:它对我有用,我看到了一顶皇冠。您必须在程序开始时执行此操作。你用的是什么版本的Windows,你用的是什么版本的VS?你还记得包括fcntl.hstdio.hio.h 吗?
  • 我的 VS 版本:2010 10.0.30319.1 RTMRel 我的 Windows 版本:Windows 7 Ultimate x32 SP1 我什么都没忘记。它只是继续向我展示那个符号,而不是皇冠。
  • @RobertEagle:是的,没有其他简单的 AFAIK 修复方法。这就是为什么通常如果您必须执行纯文本以外的任何操作,您通常会编写一个 GUI 应用程序。
  • @MatteoItalia:如果您运行 Console2,那么您也许可以绕过它,因为我认为它正确显示了 Unicode。
【解决方案2】:

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

首先,您必须在标准输出上启用 UTF-16 模式;这被描述为herehere,这与 Mehrdad 解释的完全一样。

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

...

_setmode(_fileno(stdout), _O_U16TEXT);

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

要解决此问题,您必须选择支持它们的不同 TrueType 字体,但要使此类字体可用,您必须 go through some hoops;就个人而言,我发现 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;
}

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-24
    • 2012-05-20
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多