I am working on below code:
#include<iostream> #include<stdio.h> using namespace std; main() { unsigned char a; a=1; printf("%d", a); cout<<a; }
It is printing 1 and some garbage.
Why cout
is behaving so?
printf("%02x", (unsigned int) u);
Then, how to print character? We can use cast type here, by casting into char we are able to get result in character format. We can use cout<<char(65) or cout<<char(var), that will print 'A'. (65 is the ASCII value of 'A').
unsigned char ch = 'n'; Both of the Signed and Unsigned char, they are of 8-bits. So for signed char it can store value from -128 to +127, and the unsigned char will store 0 to 255. The basic ASCII values are in range 0 to 127.
cout << a
is printing a value which appears to be garbage to you. It is not garbage actually. It is just a non-printable ASCII character which is getting printed anyway. Note that ASCII character corresponding to 1
is non-printable. You can check whether a
is printable or not using, std::isprint
as:
std::cout << std::isprint(a) << std::endl;
It will print 0
(read: false
) indicating the character is non-printable
--
Anyway, if you want your cout
to print 1
also, then cast a
to this:
cout << static_cast<unsigned>(a) << std::endl;
I had a similar issue here that I've long forgotten about. The resolution to this problem with iostream's
cout
can be done like this:
#include<iostream> #include<stdio.h> main() { unsigned char a; a=1; printf("%d", a); std::cout<< +a << std::endl; return 0; }
instead of casting it back to another type if you want cout
to print the unsigned char
value as opposed to the ascii
character. You need to promote
it.
If you noticed all I did was add a +
before the unsigned char
. This is unary addition that will promote the unsigned char
to give you the actual number representation.
User Baum mit Augen is responsible for reminding me of this solution.
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