2012-07-19 84 views
1

在下面的代碼中std::cout不打印值,但是printf。爲什麼是這樣?爲什麼std :: cout不能打印來自union的值,但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 

回答

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"; 
+1

當然......我看着森林,想知道爲什麼我會一直撞到樹林...... – slashmais 2012-07-19 12:13:58

2

它無關,與他們在工會之中。

將數據流char改爲cout會將其輸出爲字符而不是其數值;如果您指定%c而不是%d,則會出現printf

通過cout打印char的數值的最簡單方法是將其轉換爲int