[英]Why does std::cout not print values from union, but printf does?
In the following code std::cout
does not print the values, but printf
does. 在以下代码中
std::cout
不打印值,但printf
可以打印。 Why is this? 为什么是这样?
#include <iostream>
#include <cstdio>
struct bits
{
union
{
unsigned char b;
struct
{
unsigned char b0:1, b1:1, b2:1, b3:1, b4:1, b5:1, b6:1, b7:1;
};
};
};
const union
{
bits b[3];
char c[3];
} CU = { .c = { -1, 0, 1 }};
int main()
{
std::cout << "----- chars:\n";
std::cout << "\tstd::cout (c): " << CU.c[0]
<< ", " << CU.c[1]
<< ", " << CU.c[2]
<< "\n";
printf("\tprintf (c): %d, %d, %d\n", CU.c[0],
CU.c[1],
CU.c[2]);
std::cout << "\n----- bits:\n";
for (int i=0;i<3;i++)
{
std::cout << "\tstd::cout\n\t\t(bits): [" << i << "] = "
<< CU.b[i].b0 << CU.b[i].b1 << CU.b[i].b2
<< CU.b[i].b3 << CU.b[i].b4 << CU.b[i].b5
<< CU.b[i].b6 << CU.b[i].b7 << "\n";
std::cout << "\t\t(b): [" << i << "] = " << CU.b[i].b << "\n";
printf("\tprintf\n\t\t(bits): [%d] = %d%d%d%d%d%d%d%d\n",
i, CU.b[i].b0, CU.b[i].b1, CU.b[i].b2,
CU.b[i].b3, CU.b[i].b4, CU.b[i].b5,
CU.b[i].b6, CU.b[i].b7);
printf("\t\t(b): [%d] = %d\n\n", i, CU.b[i].b);
}
return 0;
}
Output: 输出:
----- chars:
std::cout (c): �, ,
printf (c): -1, 0, 1
----- bits:
std::cout
(bits): [0] =
(b): [0] = �
printf
(bits): [0] = 11111111
(b): [0] = 255
std::cout
(bits): [1] =
(b): [1] =
printf
(bits): [1] = 00000000
(b): [1] = 0
std::cout
(bits): [2] =
(b): [2] =
printf
(bits): [2] = 10000000
(b): [2] = 1
You passed the parameter %d
to printf
, telling it to read the value as an int
, but the same was not done for std::cout
, so it interprets the values as char
's and outputs the characters themselves, not their integer values. 您将参数
%d
传递给printf
,告诉它以int
读取值,但是对std::cout
却没有这样做,因此它将值解释为char
并输出字符本身,而不是其整数值。
Convert to int
first: 首先转换为
int
:
std::cout << "\tstd::cout (c): " << int(CU.c[0])
<< ", " << int(CU.c[1]) << ", " << int(CU.c[2])
<< "\n";
It has nothing to do with them being in a union. 这与他们加入工会无关。
Streaming a char
to cout
will output it as a character, rather than its numerical value; 将
char
流式传输到cout
会将其输出为字符,而不是数字值。 as printf
would if you specified %c
rather than %d
. 如果指定了
%c
而不是%d
则与printf
一样。
The simplest way to print the numerical value of a char
via cout
is to convert it to int
. 通过
cout
打印char
的数值的最简单方法是将其转换为int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.