2015-04-14 18 views
0

我有一個快速的問題,無法在其他地方找到答案。基本上我試圖做一個通用函數來返回正確的unicode(而不是文字),如下所示在std :: string getUnicode()函數中。 \ xe2 \ x99 \ xa和cardType在輸出中被視爲兩個單獨的字符串,這會導致「?」隨後是cardType號碼。C++ Universal Unicodes

在這種情況下:

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 
+0

我不知道你想要什麼。什麼是「爲您返回適當的Unicode」?該代碼可以使* UTF8的某些*感覺...以及「輸出」在哪裏?請一個MVCE。 – deviantfan

+0

cout << card.getUnicode(); //這就是「輸出」。對於心臟,黑桃,鑽石和俱樂部來說,unicode除了最後的數字外都是一樣的,我會動態地將相應的數字追加到最後。 – Gosre

回答

3

這在C被談到++標準,2.14.5節,第13段:

[實施例:

"\xA" "B" 

包含兩個字符'\xA''B'級聯後(而不是單個十六進制字符'\xAB')。 - 端示例]

的問題是,'\xa'被視爲單個字符(十六進制值0xa 10是十進制,其中映射到\n(換行)字符ASCII/UTF)。 cardType沒有被「附加」到轉義序列。事實上,轉義序列是在編譯時評估的,而不是運行時(這是卡類型被評估時)。

爲了這個工作,你需要做的是這樣的:

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

謝謝!非常明確的解釋。 – Gosre