boost format yield different output for seemingly same strings

76 Views Asked by At

Background

I am using the boost format library to format some text. My input is an uint8_t array. This is the code I used:

#include <array>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <boost/format.hpp>

int main(int ac, const char * av[]){

    std::string nameStr = "HELLO, WORLD";
    std::array<uint8_t, 30> nameArr={0x48, 0x45, 0x4e, 0x4c, 0x4f, 0x20, 0x46, 0x52, 0x45, 0x4e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    std::string convertedStr(std::begin(nameArr), std::end(nameArr));

    std::cout << "nameStr.size():" << nameStr.size() << ", nameStr.length():" << nameStr.length() << ", nameStr:" << nameStr << std::endl;
    std::cout << "convertedStr.size():" << convertedStr.size() << ", convertedStr.lenght():" << convertedStr.length() << ", convertedStr:" << convertedStr << std::endl;

    std::ostringstream oss;
    oss << boost::format("%-24s%c%-10d%8s") % nameStr % "#" % 512 % "999";

    std::cout << oss.str() + '\n';

    oss.str(std::string());

    oss << boost::format("%-24s%c%-10d%8s") % convertedStr % "#" % 512 % "999";

    std::cout << oss.str() + '\n';

    return 0;
}

Issue

The code above produce this output:

nameStr.size():10, nameStr.lenght():10, nameStr:HELLO, WORLD
convertedStr.size():30, convertedStr.lenght():30, convertedStr:HELLO, WORLD
HELLO, WORLD              #512            999
HELLO, WORLD#512            999

oss << boost::format("%-24s%c%-10d%8s") % convertedStr % "#" % 512 % "999"; gives a different output & omits -24 and starts following parts immediately.

I guessed that length of array was bigger than format length specifier might cause this, so I changed -24 to -40 at both format lines. This is the output:

nameStr.size():10, nameStr.lenght():10, nameStr:HELLO, WORLD
convertedStr.size():30, convertedStr.lenght():30, convertedStr:HELLO, WORLD
HELLO, WORLD                              #512            999
HELLO, WORLD          #512            999

Question

Is there something wrong with my code?

How can I format string converted from uint8_t array properly?

0

There are 0 best solutions below