Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cout not printing unsigned char

Tags:

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?

like image 789
Hitesh Menghani Avatar asked Mar 23 '13 09:03

Hitesh Menghani


People also ask

How do I print unsigned characters?

printf("%02x", (unsigned int) u);

How do I print a character in cout?

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

How do you declare an unsigned char in C++?

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.


2 Answers

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; 
like image 116
Nawaz Avatar answered Oct 17 '22 15:10

Nawaz


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.

like image 21
Francis Cugler Avatar answered Oct 17 '22 15:10

Francis Cugler