Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing chars as Integers

I want to control whether my ostream outputting of chars 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?

like image 521
Nordlöw Avatar asked Jun 08 '12 14:06

Nordlöw


People also ask

Can a char be an integer?

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.

Can we use %d for char?

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 .

Can a char type be a number?

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.

How do you print a char in C?

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.).


1 Answers

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.

like image 144
Michael Kristofik Avatar answered Sep 29 '22 19:09

Michael Kristofik