2015-08-26 55 views
4

找不到在線幫助。有什麼辦法可以解決這個問題嗎?解決std :: showbase不加前綴零

std::showbase只(在std::hex情況下,例如,0x)爲非零數增加了一個前綴(如所解釋here)。我想要一個格式爲0x0的輸出,而不是0

但是,僅僅使用:std::cout << std::hex << "0x" << ....不是一種選擇,因爲右側參數可能並不總是整數(或等價物)。我要尋找一個替代showbase,這將0x前綴0並不能扭曲非整數(或等價物),像這樣:

using namespace std; 

/* Desired result: */ 
cout << showbase << hex << "here is 20 in hex: " << 20 << endl; // here is 20 in hex: 0x14 

/* Undesired result: */ 
cout << hex << "0x" << "here is 20 in hex: " << 20 << endl;  // 0xhere is 20 in hex: 20 

/* Undesired result: */ 
cout << showbase << hex << "here is 0 in hex: " << 0 << endl; // here is 0 in hex: 0 

非常感謝。

+0

這真的是一個有點奇怪。即使您使用「十六進制」前綴,「0」仍以*八進制*形式打印。 :-) [0是十進制文字還是八進制文字?](http://stackoverflow.com/questions/6895522/is-0-a-decimal-literal-or-an-octal-literal) –

+0

我是不知道我是否理解你的問題,但它是一個const int&...它不會被打印爲'hex',這只是std :: showbase的定義,正如我在OP中提到的鏈接中所解釋的那樣 – alonbe

+0

這是一個內部玩笑,關於符合語法的事實,'0'是一個八進制數。即使你在十六進制中明確要求它,你也會得到。 –

回答

1

嘗試

std::cout << "here is 20 in hex: " << "0x" << std::noshowbase << std::hex << 20 << std::endl; 

這樣數量將0x始終爲前綴,但你必須添加<< "0x"每一張打印號碼前。

你甚至可以嘗試創建自己的流處理器

struct HexWithZeroTag { } hexwithzero; 
inline ostream& operator<<(ostream& out, const HexWithZeroTag&) 
{ 
    return out << "0x" << std::noshowbase << std::hex; 
} 

// usage: 
cout << hexwithzero << 20; 

爲了保持從hereoperator<<通話,使用的答案之間設置以延長自己的流。你將不得不改變區域的do_put這樣的:

const std::ios_base::fmtflags reqFlags = (std::ios_base::showbase | std::ios_base::hex); 

iter_type 
do_put(iter_type s, ios_base& f, char_type fill, long v) const { 
    if (v == 0 && ((f.flags() & reqFlags) == reqFlags)) { 
     *(s++) = '0'; 
     *(s++) = 'x'; 
    } 
    return num_put<char>::do_put(s, f, fill, v); 
} 

完整的工作方案:http://ideone.com/VGclTi