簡體   English   中英

Cout沒有打印號碼

[英]Cout not printing number

問題

我從一個簡單的cout沒有輸出,而printf將始終打印數字:

std::cout << variableuint8;  // prints nothing
printf("%u", variableuint8); // prints the number

我以前從未遇到過這種行為,雖然我有一個解決方法,但我想了解它。

語境:

耶,指針。 所以它可能比所述的更多參與。 這是上下文 - 我不認為它應該重要,當cout和printf獲取信息時,它被解除引用到一個簡單的unsigned char。 這可能是解決問題所需的更多信息,但我想完全了解它是否相關。

typedef unsigned char   UInt8;
typedef unsigned short  UInt16;

typedef struct{
   UInt8   len;
   // some other definitions. sizeof(DeviceNotification) <= 8
}DeviceNotification;

UInt8 somerandomdata[8];
DeviceNotification * notification;

notification = (DeviceNotification *) somerandomdata;

std::cout << "Len: (" << notification->len << ")\n";
printf("Len: (%u)\n", notification->len);

隨機數據在別處初始化。 對於此輸出,數組中的第一個字節是0x08:

輸出:

Len: ()
Len: (8)

環境

  • 開發機器:
    • OS X 10.6.8
    • 編譯器LLVM 1.7
    • Xcode 3.2.6
  • 試驗機:
    • OS X 10.6.8

它將char打印為角色。

#include <iostream>

int main() {
        unsigned char c = 0x41;
        std::cout << c << std::endl;
        return 0;
}

這會將'A'打印到標准輸出。

雖然在這種情況下,你的代碼應該打印Len: (*) ,我確實已經驗證它打印Len: (*)


編輯:由於在控制台可能正在使用的ASCII或UTF-8等字符編碼中,對應於8(Backspace)的字符不可見,它看起來好像沒有打印。

(在某些情況下,它可能會導致前一個字符( ( )消失,因為它是退格字符。在DOS中它可能顯示◘)

您是否嘗試將其強制轉換為int,以避免依賴於實現使用的char類型:

std::cout << (int)variableuint8;

以下是對正在發生的事情的解釋: 什么是unsigned char?

為了獲得一個想法,您的實現使用unsigned char作為char 0x08的ASCII代碼是退格控制字符,當然它不是可打印的字符,這就是為什么在std::cout的情況下你看不到輸出的原因。

std::cout << "Len: (" << (unsigned short)notification->len << ")\\n"; 打印正確的值? 我猜可能正在尋找一個整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM