2

在下面的代码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
4

2 回答 2

5

您将参数传递%dprintf,告诉它将值读取为int,但对 没有执行相同的操作std::cout,因此它将值解释为char' 并输出字符本身,而不是它们的整数值。

转换为int第一个:

std::cout << "\tstd::cout (c): " << int(CU.c[0])
          << ", " << int(CU.c[1]) << ", " << int(CU.c[2])
          << "\n";
于 2012-07-19T12:09:00.537 回答
2

这与他们是否加入工会无关。

流式传输chartocout会将其输出为字符,而不是其数值;就像printf您指定%c而不是%d.

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

于 2012-07-19T12:10:19.507 回答