C++ Custom I/O manipulator for hexadecimal integers

Viewed 320

I'm trying to write a custom I/O manipulator in C++ which can write nicely formatted hexadecimals in the form 0xFFFF according to the size of the provided integer.

For example:

  • char c = 1 becomes 0x01
  • short s = 1 becomes 0x0001

And so on. Can't find the error in my code, which is printing garbage:

#include <iostream>
#include <iomanip>


class hexa_s
{
   mutable std::ostream *_out;

   template<typename T>
   const hexa_s& operator << (const T & data) const
   {
       *_out << std::internal << std::setfill( '0' ) << std::hex << std::showbase << std::setw( sizeof( T ) * 2 ) << data;

       return *this;
   }

   friend const hexa_s& operator <<( std::ostream& out, const hexa_s& b )
   {
       b._out = &out;
       return b;
   }
};

hexa_s hexa( )
{
    return hexa_s( );
}


int main()
{
    int value = 4;

    std::cout << hexa << value << std::endl;

    return 0;
}
2 Answers
Related