格式化我經常做這樣的事情:C++插入到流與十六進制
uint8_t c=some_value;
std::cout << std::setfill('0') << std::setw(2);
std::cout << std::hex << int(c);
std::cout << std::setfill(' ');
(特別是反傾銷的同時調試信息)。那豈不是不錯的東西manipulatorish我可以把在這樣的流:
的std ::法院< < 「C值:0X」 < < HEXB(C)< < '\ n';
那會做所有這些?有誰知道這是怎麼做到的嗎?
我已經得到這個工作,但希望能有一個簡單的方法:
#include <iostream>
#include <iomanip>
class hexcdumper{
public:
hexcdumper(uint8_t c):c(c){};
std::ostream&
operator()(std::ostream& os) const
{
// set fill and width and save the previous versions to be restored later
char fill=os.fill('0');
std::streamsize ss=os.width(2);
// save the format flags so we can restore them after setting std::hex
std::ios::fmtflags ff=os.flags();
// output the character with hex formatting
os << std::hex << int(c);
// now restore the fill, width and flags
os.fill(fill);
os.width(ss);
os.flags(ff);
return os;
}
private:
uint8_t c;
};
hexcdumper
hexb(uint8_t c)
{
// dump a hex byte with width 2 and a fill character of '0'
return(hexcdumper(c));
}
std::ostream& operator<<(std::ostream& os, const hexcdumper& hcd)
{
return(hcd(os));
}
當我這樣做:
std::cout << "0x" << hexb(14) << '\n';
- HEXB(三)被調用和返回hexcdumper的構造函數保存c
- 重載運算符< <用於hexcdumper調用 hexcdumper :: operator ()傳遞流
- hexcdumper的運營商()做所有的魔法爲我們
- hexcdumper後::運算符()返回時,重載操作符< < 收益從hexcdumper ::運算符的流()等等鏈接作品。
在輸出時,我看到:
0x0e
有沒有一種簡單的方法來做到這一點?
帕特里克
您認爲您的解決方案有什麼問題?對我來說看起來不錯,如果它做到了你想要的。 **優雅**已過時! –