Home > Backend Development > C++ > body text

Why Doesn\'t `cout` Print Unsigned Characters Correctly in C ?

DDD
Release: 2024-11-27 06:01:08
Original
127 people have browsed it

Why Doesn't `cout` Print Unsigned Characters Correctly in C  ?

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;
}
Copy after login

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;
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template