2015-09-18 30 views
1

如果num的類型爲int,那麼此程序將工作。但是當將其更改爲int8_t時,num將在scanf()後始終爲0。int8_t類型的變量總是從scanf獲得值0

這是因爲%dscanf

#include <stdio.h> 
#include <stdint.h> 
void convert(int8_t, int8_t); 

int main(int argc, char const *argv[]) { 
    int8_t num; 
    int8_t b; 
    printf("enter a number:\n"); 
    while (1 == scanf("%d", &num)) { 
     scanf("%d", &b); 
     printf("%d %d\n", num, b); 
     printf("Code: "); 
     convert(num, b); 
     putchar('\n'); 
     printf("enter a integer (q to quit):\n"); 
    } 
    printf("done.\n"); 

    getchar(); 
    return 0; 
} 

void convert(int8_t n, int8_t base) { 
    if (n >= base) 
     convert(n/base, base); 
    printf("%d", n % base); 
    return; 
} 
+6

1)閱讀'scanf'手冊,2)啓用編譯器警告,3)不對編譯器說謊。 –

+0

http://en.cppreference.com/w/c/types/integer檢查格式部分 –

回答

1

%d格式說明爲scanf期望參數是一個int的地址,這是在大多數系統4或8個字節。你傳遞一個int8_t的地址,它只有1個字節。因此,scanf將結果值寫入4-8字節而不是1,導致未定義的行爲。

您需要使用%hhd,它需要指向char(與相同)作爲其參數。

+3

正確的格式說明在'inttypes.h':'SCNd8'中。 – Olaf

5

您將錯誤的參數傳遞給scanf,%d預計地址爲int

您可以使用宏SCNd8來輸入int8_t。標題<intypes.h>

scanf("%"SCNd8, &b); 

和宏PRId8來打印它的值。