1

我有以下课程(仅部分课程,课程中有更多字段)

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();
      }
}

我想在 toString 方法中添加一个格式化的 mac(带 :)?有没有一种简单的方法来采用我的 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]);
}
4

3 回答 3

3

使用IO 操纵器

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]);
}
于 2012-10-02T15:07:30.957 回答
2

您可以用 sprintf 替换您对 printf 的使用,然后使用它来实现 operator<< 用于 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';
}
于 2012-10-02T15:32:09.043 回答
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];
于 2012-10-02T15:08:44.340 回答