Search code examples
c++arraysboostboost-format

Boost::Format with char array


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++


Solution

  • 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