cout不打印unsigned char [英] cout not printing unsigned char
问题描述
我正在处理以下代码:
#include<iostream>
#include<stdio.h>
using namespace std;
main() {
unsigned char a;
a=1;
printf("%d", a);
cout<<a;
}
正在打印1和一些垃圾。
It is printing 1 and some garbage.
为什么 cout
表现如此?
推荐答案
cout< a
正在打印一个看起来是垃圾的值。它实际上不是垃圾。它只是一个不可打印的 ASCII字符,无论如何它仍然打印。请注意,对应于 1
的ASCII字符是不可打印的。您可以检查 a
是否可以打印, std :: isprint
as:
cout << a
is printing a value which appears to be garbage to you. It is not garbage actually. It is justa 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;
它将打印 0
code> false )表示字符不可打印
It will print 0
(read: false
) indicating the character is non-printable
-
无论如何,如果你也希望 cout
打印 1
到此:
Anyway, if you want your cout
to print 1
also, then cast a
to this:
cout << static_cast<unsigned>(a) << std::endl;
这篇关于cout不打印unsigned char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!