Home > OS >  how to use std::num_put for custom pointer output formatting?
how to use std::num_put for custom pointer output formatting?

Time:11-09

TLDR;

Default output of pointers with c iostream is of the form 0xdeadbeef. What I want is pointers to be output in the form #xdeadbeef.

Problem

For testing purposes I output internal data of some c program in form of s-expressions, so I can have in the future the option to use Common Lisp to reason about the output. Now, hex numbers are written in the form #xdeadbeef and iostream default is using the C/C typical 0x... syntax.

So, after a bit of reading, I think I am close to finding a solution... only, at least on cppreference.com, there is not enough (demo code or explanations) to allow me to understand, how I am exactly supposed to solve this.

#include <iostream>
#include <locale>
#include <sstream>
#include <string>

struct lispy_num_put : std::num_put<char> {
  iter_type do_put(iter_type s, std::ios_base& f,
           char_type fill, const void* p) {
    std::ostringstream oss;
    oss << p;
    std::string zwoggle{oss.str()};
    if (zwoggle.length() > 2 && zwoggle.starts_with("0x")) {
      zwoggle[0] = '#';
    }
    // ... NOW WHAT TO DO??? I.e how to send the string along?
  }
};
// ...

As you can see, I now have the string representation of how I want to see the pointer in the output. Only it is unclear to me, how to send that string now into the output stream.

Later, I will have to use some imbue() thingy to make this struct used by my output stream. I think, that part I can figure out myself.

CodePudding user response:

Use your iter_type s parameter to output characters.

*s   = '#'; // outputs a hash 
while (...) *s   = ...; // outputs digits
return s;
  • Related