使用scanf读取unsigned char

use*_*997 20 c scanf

我正在尝试使用此代码读取0到255(unsigned char)之间的值.

#include<stdio.h>
int main(void)
{
    unsigned char value;

    /* To read the numbers between 0 to 255 */
    printf("Please enter a number between 0 and 255 \n");
    scanf("%u",&value);
    printf("The value is %u \n",value);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我按预期得到了以下编译器警告.

warning: format ‘%u’ expects type ‘unsigned int *’, but argument 2 has type ‘unsigned char *’

这是我对该计划的输出.

Please enter a number between 0 and 255
45
The value is 45 
Segmentation fault

运行此代码时,我确实遇到了分段错误.

unsigned char使用读取值的最佳方法是什么scanf

Joe*_*Joe 36

%u说明符需要一个整数读取到时会导致不确定的行为unsigned char.您将需要使用说明unsigned char%hhu.