I have a weird problem about working with integers in C++.
I wrote a simple program that sets a value to a variable and then prints it, but it is not working as expected.
My program has only two lines of code:
uint8_t aa = 5;
cout << "value is " << aa << endl;
The output of this program is value is
I.e., it prints blank for aa
.
When I change uint8_t
to uint16_t
the above code works like a charm.
I use Ubuntu 12.04 (Precise Pangolin), 64-bit, and my compiler version is:
gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
As others said before the problem occurs because standard stream treats signed char and unsigned char as single characters and not as numbers.
Here is my solution with minimal code changes:
Adding
"+0"
is safe with any number including floating point.For integer types it will change type of result to
int
ifsizeof(aa) < sizeof(int)
. And it will not change type ifsizeof(aa) >= sizeof(int)
.This solution is also good for preparing
int8_t
to be printed to stream while some other solutions are not so good:Output:
P.S. Solution with ADL given by pepper_chico and πάντα ῥεῖ is really beautiful.
Adding a unary + operator before the variable of any primitive data type will give printable numerical value instead of ASCII character(in case of char type).
cout
is treatingaa
aschar
of ASCII value5
which is an unprintable character, try typecasting toint
before printing.uint8_t
will most likely be atypedef
forunsigned char
. Theostream
class has a special overload forunsigned char
, i.e. it prints the character with the number 5, which is non-printable, hence the empty space.Making use of ADL (Argument-dependent name lookup):
output:
A custom stream manipulator would also be possible.
cout << +i << endl
).It doesn't really print a blank, but most probably the ASCII character with value 5, which is non-printable (or invisible). There's a number of invisible ASCII character codes, most of them below value 32, which is the blank actually.
You have to convert
aa
tounsigned int
to output the numeric value, sinceostream& operator<<(ostream&, unsigned char)
tries to output the visible character value.