C++ 通用 Unicode

C++ Universal Unicodes

我有一个简短的问题,但在其他任何地方都找不到答案。基本上,我试图制作一个通用函数 return 正确的 unicode(而不是制作文字),如下面的 std::string getUnicode() 函数所示。 \xe2\x99\xa 和 cardType 在输出中被视为两个单独的字符串,这会导致“?”然后是卡类型编号。

在这种情况下:

cout << "\xe2\x99\xa0"; //prints out a symbol, GOOD
cout << "\xe2\x99\xa" << 0; //prints out "?" followed by 0. BAD
cout << card.getUnicode(); //prints out "?" followed by 0. BAD

有什么想法吗? 4-6 个月的 C++ 初学者。

#ifndef CARD_H
#define CARD_H

#include <map>
#include <sstream>
#include <string>

enum CARD_TYPE {SPADE = 0, CLUB = 3, HEART = 5, DIAMOND = 6};

class Card {

    private:
        int number;
        CARD_TYPE cardType;

    public:
        Card(CARD_TYPE, int);
        void displayCard();

        int getNumber() {
            return number;
        }

        CARD_TYPE getCardType() {
            return cardType;
        }

        /* Returns Unicode Value for this Card Type */
        std::string getUnicode() {
            std::stringstream ss;
            ss << "\xe2\x99\xa" << cardType;
            return ss.str();
        }

};

#endif

C++ 标准第 2.14.5 节第 13 段中谈到了这一点:

[Example:

"\xA" "B"

contains the two characters '\xA' and 'B' after concatenation (and not the single hexadecimal character '\xAB'). — end example ]

问题是 '\xa' 被视为单个字符(十六进制值 0xa 是十进制的 10,它映射到 \n(换行)字符 ASCII/UTF)。 cardType 没有得到 "appended" 转义序列。事实上,转义序列是在编译时评估的,而不是运行时(这是评估卡片类型的时间)。

为了让它工作,你需要做类似的事情:

 ss << "\xe2\x99" << static_cast<char>(0xa0 + cardType);