首页 > 解决方案 > A problem with the behaviour of scanf when data type is unsigned char

问题描述

So I have no idea why this behavior is observed:

#include <stdio.h>

int main()
{
    unsigned char c;
    char d;
    scanf("%hhu", &d);
    printf("%c\n", d);

    return 0;
}

If I remember correctly %hhu is for unsigned char. If I input almost any character like a, or b the answer is nothing and d gets the value 0. But if I input 97 then d prints the value a (so ASCII is converted to char). This clearly not the case when the data type is char. I can just input the character directly and it is stored.

Also in the slight modification of this code

#include <stdio.h>

int main()
{
    unsigned char c;
    char d;
    int g;
    scanf("%hhu", &d);
    printf("%c\n", d);
    scanf("%d", &g);
    printf("%d is g\n", g);

    return 0;
}

If I give first input as a character like w or a then it just skips the second scanf, but if the input is a number then it works normally.

标签: cscanfunsigned-char

解决方案


您是正确的,%hhu格式说明符需要一个unsigned char*参数。但是,u格式的一部分规定将输入解释为十进制整数。要将数据作为(未处理的)字符输入,您应该使用%c格式说明符。


推荐阅读