0

I'm executing the following code, have read this:

Escaping a C++ string

#include <iostream>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>

struct CharacterEscaper
{
    template<typename FindResultT>
    std::string operator()(const FindResultT& Match) const
    {
        std::string s;
        for (typename FindResultT::const_iterator i = Match.begin();i != Match.end();i++) 
        {
            s += str(boost::format("\\x%02x") % static_cast<int>(*i));
        }
        return s;
    }
};

int main (int argc, char **argv)
{
    std::string s("start\x0aend");
    boost::find_format_all(s, boost::token_finder(!boost::is_print()), CharacterEscaper());
    std::cout << s << std::endl;
    return 0;
}

The output I'm getting is this:

start\xffffffaend

I was expecting the following:

start\x0aend

having read this:

http://en.cppreference.com/w/cpp/language/escape

What is correct?

Community
  • 1
  • 1
Baz
  • 12,713
  • 38
  • 145
  • 268

2 Answers2

1

Two issues here:

  • The escaper converts the character value to int before formatting it. This means that, if char is signed, values above 0x7f will be sign-extended, giving the extra fs in the output. You can fix that by converting first to unsigned char, then perhaps to unsigned or int. (I don't know enough about the Boost formatter to know whether the second converion is necessary.)
  • A hexadecimal escape sequence will include as many hexadecimal digits as it can find, so in this case it will be \x0ae. One way to fix that is by breaking the string literal into two, which will be recombined during compilation: "start\x0a" "end"
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

I think I have the answer. I should have written this: "start\x0a" "end"

MSalters
  • 173,980
  • 10
  • 155
  • 350
Baz
  • 12,713
  • 38
  • 145
  • 268