std::cout 输出 unsigned char类型数据

写C++代码的时候可能发现,输出char, float, int, 还有double 等类型的时候正常,但是遇到unsigned char有时候就输出乱码。
所以自己测试一下:

int main(int argc, char** argv) { std::cout << "test for uchar" << std::endl; int h = 255; //unsigned char u = (unsigned char)(h); unsigned char u = '255'; char c = 'a'; float f = 1.0f; double d = 1.0f; int i = 1; std::cout << "unsigned char: " << u << std::endl; std::cout << "char: " << c << std::endl; std::cout << "float: " << f << std::endl; std::cout << "double: " << d << std::endl; std::cout << "int: " << i << std::endl; }

输出的结果正常:
std::cout 输出 unsigned char类型数据
文章图片

unsigned char 一般是0-255之间,当我们赋值的方式给予一个值的时候:
int main(int argc, char** argv) { std::cout << "test for uchar" << std::endl; int h = 255; unsigned char u = (unsigned char)(h); //unsigned char u = '255'; char c = 'a'; float f = 1.0f; double d = 1.0f; int i = 1; std::cout << "unsigned char: " << u << std::endl; std::cout << "char: " << c << std::endl; std::cout << "float: " << f << std::endl; std::cout << "double: " << d << std::endl; std::cout << "int: " << i << std::endl; }

输出的结果为垃圾值:
std::cout 输出 unsigned char类型数据
文章图片

It will not work because here u(unsigned char) is a unsigned char (with value 255), cout actually will print some garbage value (or nothing) as it is just a non-printable ASCII character which is getting printed anyway. Note that ASCII character corresponding to 255 is non-printable. Check out here for the ASCII table.
P.S. You can check whether u is printable or not using isprint() as
上面的意思是:当赋予这个超过了ASCII的范围了,所以打印不出来,或者是垃圾值。
最后测试:
当赋予u为正常的正常的值的时候,97对应为’a’,输出为‘a’,测试结果如下:
测试代码:
int main(int argc, char** argv) { std::cout << "test for uchar" << std::endl; int h = 97; unsigned char u = (unsigned char)(h); //unsigned char u = '255'; char c = 'a'; float f = 1.0f; double d = 1.0f; int i = 1; std::cout << "unsigned char: " << u << std::endl; std::cout << "char: " << c << std::endl; std::cout << "float: " << f << std::endl; std::cout << "double: " << d << std::endl; std::cout << "int: " << i << std::endl; }

【std::cout 输出 unsigned char类型数据】测试结果
std::cout 输出 unsigned char类型数据
文章图片

所以,std::cout出不来的时候,可以用强制转换为int,cout就可以了。
代码如下:
int main(int argc, char** argv) { std::cout << "test for uchar" << std::endl; int h = 255; unsigned char u = (unsigned char)(h); //unsigned char u = '255'; char c = 'a'; float f = 1.0f; double d = 1.0f; int i = 1; std::cout << "unsigned char: " << (int)u << std::endl; std::cout << "char: " << c << std::endl; std::cout << "float: " << f << std::endl; std::cout << "double: " << d << std::endl; std::cout << "int: " << i << std::endl; }

测试的结果:
std::cout 输出 unsigned char类型数据
文章图片

参见的材料如下:
https://www.it1352.com/457126.html

    推荐阅读