2012-10-02 31 views
1

我有下面的類(只是部分,更多的類中字段)寫格式化MAC地址字符串流

class Network{ 
public: 
     string src_ip_; 
     string alternative_src_ip_; 
     array<unsigned char,6> mac_; 
     string toString(){ 
      stringstream ss; 
      ss << src_ip_ << SEPERATOR << alternative_src_ip_ << SEPERATOR ; 
      return ss.str(); 
     } 
} 

我想添加一個格式化的MAC(與:)的toString方法? 有沒有采納我printMac法(generelize或寫入新的),將做到這與結合在< <操作

void printMac(array<unsigned char, 6> mac) { 
    printf("%02x:%02x:%02x:%02x:%02x:%02x\n", 
      (unsigned char) mac[0], (unsigned char) mac[1], 
      (unsigned char) mac[2], (unsigned char) mac[3], 
      (unsigned char) mac[4], (unsigned char) mac[5]); 
} 
+0

只是要reeeally OCD和挑剔,一般惱人的,我想如果你愛它'd改變你的常數* SEPARATOR :) –

+0

@ AK4749謝謝! :)好評:) –

回答

2

你可以用sprintf的更換你的printf的使用,然後用它來實現操作< <爲ostreams

void printMac(array<unsigned char, 6> mac, char (&out)[18]) { 
    sprintf(out, "%02x:%02x:%02x:%02x:%02x:%02x", 
      (unsigned char) mac[0], (unsigned char) mac[1], 
      (unsigned char) mac[2], (unsigned char) mac[3], 
      (unsigned char) mac[4], (unsigned char) mac[5]); 
} 

std::ostream &operator<<(std::ostream &os, std::array<unsigned char, 6> mac) { 
    char buf[18]; 
    printMac(mac, buf); 
    return os << buf << '\n'; 
} 
+0

愚蠢的問題 - 如果我理解正確的最後一個字符是\ 0終止?我在buf [17]中使用,並沒有任何問題,所以我們爲什麼需要使用18字節的? –

+1

@ user1495181是的,有一個額外的空間來容納空終止符。如果你沒有它,那麼sprintf將寫入數組之外,這會導致[undefined behavior](http://en.wikipedia.org/wiki/Undefined_behavior)。 – bames53

3

使用IO manipulators一個簡單的方法:

std::ostringstream s; 
unsigned char arr[6] = { 0, 14, 10, 11, 89, 10 }; 

s << std::hex << std::setfill('0'); 

for (int i = 0; i < sizeof(arr); i++) 
{ 
    if (i > 0) s << ':'; 

    // Need to: 
    // - set width each time as it only 
    // applies to the next output field. 
    // - cast to an int as std::hex is for 
    // integer I/O 
    s << std::setw(2) << static_cast<int>(arr[i]); 
} 
0

如果你想維護類似printf的代碼,你可以試試Boost.Format

ss << boost::format("%02x:%02x:%02x:%02x:%02x:%02x\n") % mac[0] % mac[1] % mac[2] % mac[3] % mac[4] % mac[5];