Printing characters as integers

I want to control whether my ostream outputs char and unsigned char output via << them as characters or integers. I can not find such an option in the standard library. At the moment, I’ve returned to using several overloads in the set of alternative printing functions.

 ostream& show(ostream& os, char s) { return os << static_cast<int>(s); } ostream& show(ostream& os, unsigned char s) { return os << static_cast<int>(s); } 

Is there a better way?

+7
source share
3 answers

No, there is no better way. A better way would be to form a custom stream manipulator like std::hex . You can then turn off and turn off the whole print without having to specify it for each number. But custom manipulators work on the thread itself, and there are no format flags to do what you want. I suppose you could write your own thread, but in this case more work than now.

Honestly, it's best to see if your text editor has functions to make it easier to enter static_cast<int> . I suppose you would write a lot of it otherwise, or you would not ask. This way, someone who reads your code knows exactly what you mean (i.e. type char as an integer) without having to look for a definition of a custom function.

+1
source

I have a suggestion based on the method used in how can I print unsigned char as hex in C ++ using ostream? .

 template <typename Char> struct Formatter { Char c; Formatter(Char _c) : c(_c) { } bool PrintAsNumber() const { // implement your condition here } }; template <typename Char> std::ostream& operator<<(std::ostream& o, const Formatter<Char>& _fmt) { if (_fmt.PrintAsNumber()) return (o << static_cast<int>(_fmt.c)); else return (o << _fmt.c); } template <typename Char> Formatter<Char> fmt(Char _c) { return Formatter<Char>(_c); } void Test() { char a = 66; std::cout << fmt(a) << std::endl; } 
0
source

Just updating the old post. The actual trick uses a "+". For example:

 template <typename T> void my_super_function(T x) { // ... std::cout << +x << '\n'; // promotes x to a type printable as a number, regardless of type // ... } 

In C ++ 11 you can do:

 template <typename T> auto promote_to_printable_integer_type(T i) -> decltype(+i) { return +i; } 

Credit: How to print char as number? How can I print char * so that the output displays the numeric value of the pointer?

0
source

All Articles