int8_t类型的变量始终从scanf获取值0

时间:2015-09-18 17:31:25

标签: c

如果num的类型为int,此程序将有效。但是,当将其更改为int8_t时,numscanf()将始终为0。

这是因为%d中的scanf吗?

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

2 个答案:

答案 0 :(得分:5)

您将错误的参数传递给scanf%d需要int的地址。

您可以使用宏SCNd8来获取int8_t的输入。标题<intypes.h>

scanf("%"SCNd8, &b);

PRId8打印其值。

答案 1 :(得分:1)

%d的{​​{1}}格式说明符要求参数为scanf的地址,在大多数系统上为4或8字节。您将int的地址传递给它,该地址只有1个字节。因此int8_t将结果值写入4-8个字节而不是1,从而导致未定义的行为。

您需要使用scanf,它需要指向%hhd(与char相同)的指针作为其参数。