I can make an std::ostream object output integer numbers in hex, for example
std::cout << std::hex << 0xabc; //prints `abc`, not the base-10 representation
Is there any manipulator that is universal for all bases? Something like
std::cout << std::base(4) << 20; //I want this to output 110
If there is one, then I have no further question.
If there isn’t one, then can I write one? Won’t it require me to access private implementation details of std::ostream?
Note that I know I can write a function that takes a number and converts it to a string which is the representation of that number in any base. Or I can use one that already exists. I am asking about custom stream manipulators – are they possible?
You can do something like the following. I have commented the code to explain what each part is doing, but essentially its this:
xallocandiword.num_putfacet which looks for your manipulator and applies the manipulation.Here is the code…
Edit: Note that im not sure I handled the
std::ios_base::internalflag correctly here – as I dont actually know what its for.Edit 2: I found out what
std::ios_base::internalis for, and updated the code to handle it.Edit 3: Added a call to
std::locacle::globalto show how to make all the standard stream classes support the new stream manipulator by default, rather than having toimbuethem.