为什么std :: cout不能从union打印值,但是printf有吗?

时间:2012-07-19 12:04:59

标签: c++ printf cout

在以下代码std::cout中不会打印值,但printf会打印。这是为什么?

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

输出:

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

2 个答案:

答案 0 :(得分:5)

您将参数%d传递给printf,告诉它将值读作int,但std::cout没有这样做,所以它解释了值为char&并且输出字符本身,而不是它们的整数值。

首先转换为int

std::cout << "\tstd::cout (c): " << int(CU.c[0])
          << ", " << int(CU.c[1]) << ", " << int(CU.c[2])
          << "\n";

答案 1 :(得分:2)

与他们在工会中没有任何关系。

char流式传输到cout会将其输出为字符,而不是其数值;如果您指定printf而不是%c,则为%d

通过char打印cout的数值的最简单方法是将其转换为int