写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;
}
输出的结果正常:
文章图片
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;
}
输出的结果为垃圾值:
文章图片
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出不来的时候,可以用强制转换为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;
}
测试的结果:
文章图片
参见的材料如下:
https://www.it1352.com/457126.html
推荐阅读
- c++|相机位姿和相机外参定义以及它们的关系(画出相机位置)
- #|常用C/C++开源库
- c++|c++ 分布式令牌桶_分布式之流量控制
- 算法|二进制,八进制,十进制,十六进制的相互转换【简单易懂】
- c++|动手打造深度学习框架(基本数据结构与算法)
- C++|基于协程io_uring 异步网络库系列 III( Proactor、异步与协程 | C++20 coroutine 教程 | io_uring 异步IO 网络框架 系列笔记)
- cpp|c++入门学习——使用C++做一个yolov5视频检测
- C++|C++学习——共勉(一)
- C++从入门到放弃|c++学习笔记1(实验1)_封装CMatrix类