Home >Backend Development >C++ >Why Doesn\'t `cout` Print Unsigned Characters Correctly in C ?

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

DDD
DDDOriginal
2024-11-27 06:01:08145browse

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;
}

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!

Statement:
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