I want to control whether my ostream
outputting of char
s and unsigned char
's via <<
writes them as characters or integers. I can't find such an option in the standard library. For now I have reverted to using multiple overloads on a set of alternative print 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?
Char is an "Integer Data Type" in C and its related progeny. As per the K&R Book, "By definition, chars are just small integers". They are used for storing 'Character' data. The ASCII Table lists 128 characters, and each text character corresponds to an integer value.
The behaviour of your program is undefined. You should check the return value of scanf , which tells you the number of data that are read into the passed arguments. In your case the return value will be zero, as %d cannot be used to read in a char .
The CHAR data type stores any string of letters, numbers, and symbols. It can store single-byte and multibyte characters, based on the database locale. The CHARACTER data type is a synonym for CHAR.
printf(char *format, arg1, arg2, …) This function prints the character on standard output and returns the number of character printed, the format is a string starting with % and ends with conversion character (like c, i, f, d, etc.).
No, there isn't a better way. A better way would take the form of a custom stream manipulator, like std::hex
. Then you could turn your integer printing off and on without having to specify it for each number. But custom manipulators operate on the stream itself, and there aren't any format flags to do what you want. I suppose you could write your own stream, but that's way more work than you're doing now.
Honestly, your best bet is to see if your text editor has functions for making static_cast<int>
easier to type. I assume you'd otherwise type it a lot or you wouldn't be asking. That way someone who reads your code knows exactly what you mean (i.e., printing a char as an integer) without having to look up the definition of a custom function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With