Boost::Format with char array

1.6k Views Asked by At

I've looked around and I've been unable to find a solution to storing what is returned from a boost format into a char array. For example:

#include "stdafx.h"
#include <iostream>
#include <boost/format.hpp>

int main()
{
    unsigned int arr[5] = { 0x05, 0x04, 0xAA, 0x0F, 0x0D };
    char buf[1024];
    buf[] = boost::format("%02X-%02X-%02X-%02X-%02X") // error on this line
        % arr[0]
        % arr[1]
        % arr[2]
        % arr[3]
        % arr[4];
    system("pause");
    return 0;
}

I get the error:

error: expected an expression

I don't know if I'm just overlooking a simple solution, but I need a const char* in return. There's large amounts of code that can't be rewritten for now. I'm working on VS2013 C++

2

There are 2 best solutions below

3
sehe On BEST ANSWER

You can use an array_sink from boost iostreams:

Live On Coliru

#include <iostream>
#include <boost/format.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>

namespace io = boost::iostreams;

int main()
{
    unsigned int arr[5] = { 0x05, 0x04, 0xAA, 0x0F, 0x0D };
    char buf[1024];

    io::stream<io::array_sink> as(buf);

    as << boost::format("%02X-%02X-%02X-%02X-%02X")
        % arr[0]
        % arr[1]
        % arr[2]
        % arr[3]
        % arr[4];


    // to print `buf`:
    std::cout.write(buf, as.tellp());
}

Prints

05-04-AA-0F-0D
0
vitaut On

You could use the {fmt} library as a faster alternative to Boost Format. It allows formatting directly into a character array:

#include <fmt/format.h>

int main() {
  unsigned int arr[5] = { 0x05, 0x04, 0xAA, 0x0F, 0x0D };
  char buf[1024];
  fmt::format_to(buf, "{:02X}-{:02X}-{:02X}-{:02X}-{:02X}",
                 arr[0], arr[1], arr[2], arr[3], arr[4]);
}

or, even better, it can allocate the array automatically (in this case it will be allocated entirely on stack so no performance loss compared to a fixed buffer):

#include "format.h"

int main() {
  unsigned int arr[5] = { 0x05, 0x04, 0xAA, 0x0F, 0x0D };
  fmt::memory_buffer buf;
  fmt::format_to(buf, "{:02X}-{:02X}-{:02X}-{:02X}-{:02X}",
                 arr[0], arr[1], arr[2], arr[3], arr[4]);
}

The library uses Python-like format string syntax although safe printf implementation is also provided.

Disclaimer: I'm the author of this library.