cout Failing to Print Unsigned Character: Resolving the Issue
In C , the issue of cout not printing unsigned char is often encountered. To understand this, let's analyze the code example provided:
#include<iostream> #include<stdio.h> using namespace std; main() { unsigned char a; a = 1; printf("%d", a); cout << a; }
In this code, the unsigned char variable a is assigned the value 1. When printing a using printf, the result is "1." However, the output using cout << a displays a seemingly random character.
The reason for this discrepancy is that unsigned char can store values from 0 to 255. When a is 1, it corresponds to the non-printable ASCII character 'SOH' (start of heading). printf handles non-printable characters differently than cout.
To determine if a character is printable, use the std::isprint function:
std::cout << std::isprint(a) << std::endl;
This will print "0," indicating that 'SOH' is non-printable.
To force cout to print 1, cast a to an unsigned integer:
cout << static_cast<unsigned>(a) << std::endl;
This will successfully print "1."
Understanding the fundamental difference between printf and cout in handling non-printable characters is crucial to resolving this issue. Additionally, std::isprint can help determine whether a character should be printed in a human-readable form.
The above is the detailed content of Why Doesn\'t `cout` Print Unsigned Characters Correctly in C ?. For more information, please follow other related articles on the PHP Chinese website!