即使给出“%hhu”也无法读取unsigned char

时间:2013-08-07 08:13:09

标签: visual-c++

我的代码有问题,当我从键盘读取3个unsigned char时,它没有按预期工作,我已经使用fflush()来刷新缓冲区,但第二个变量可以从键盘获取值。这是我的代码:

void main(){
    // input Date from keyboard
    unsigned char tmpDayOfWeek;
    unsigned char tmpDay;
    unsigned char tmpMonth;
    unsigned int tmpYear;
    printf("Please input your date:\n");
    printf("  Day of Week (0 for Sunday, 1 for Monday,...): "); 
    fflush(stdin);
    scanf("%hhu", &tmpDayOfWeek);
    printf("  Day (1..31): ");
    fflush(stdin);
    scanf("%hhu", &tmpDay);
    printf("  Month (1..12): ");
    fflush(stdin);
    scanf("%hhu", &tmpMonth);
    printf("  Year (1900..9999): ");
    fflush(stdin);
    scanf("%u", &tmpYear);
    printf(" dow = %d\n", tmpDayOfWeek);
    printf(" Day = %d\n", tmpDay);
    printf(" Month = %d\n", tmpMonth);
    printf(" Year = %d\n", tmpYear);

    fflush(stdin);
    cin.get();
    return;
}

当我运行此代码并从键盘3,4,5和2000输入时,输出为:

dow = 3 
Day = 0 
Month = 5 
Year = 2000

tmpDay的值为0,尽管我输入4 任何人都帮助我, 谢谢, HoangVi P / S:我使用VC ++ 2005

1 个答案:

答案 0 :(得分:0)

没有格式说明符允许将'unsigned char'解析为“value”!

请阅读以下文档:

使用scanf解析的“shortes”值为short unsigned int => %hu