unsigned short int的格式说明符是什么?

时间:2012-01-02 10:35:46

标签: c scanf

我有以下程序

#include <stdio.h>

int main(void)
{
    unsigned short int length = 10; 

    printf("Enter length : ");
    scanf("%u", &length);

    printf("value is %u \n", length);

    return 0;
}

使用gcc filename.c编译时发出以下警告(在scanf()行中)。

warning: format ‘%u’ expects argument of type ‘unsigned int *’, but argument 2 has type ‘short unsigned int *’ [-Wformat]

然后我引用了C99 specification - 7.19.6 Formatted input/output functions并且在使用长度修饰符(例如shortlong等)与unsigned进行{int时无法理解正确的格式说明符{1}}数据类型。

%u是正确的说明符unsigned short int吗?如果是这样,为什么我得到上述警告?!

编辑: 大多数时候,我正在尝试%uh并且它仍在发出警告。

4 个答案:

答案 0 :(得分:141)

尝试使用"%h"修饰符:

scanf("%hu", &length);
        ^
  

ISO / IEC 9899:201x - 7.21.6.1-7

     

指定以下d,i,o,u,x,X或n转换   说明符适用于类型指向short或的指针的参数   unsigned short

答案 1 :(得分:43)

对于scanf,您需要使用%hu,因为您将指针传递给unsigned short。对于printf,由于默认促销而无法传递unsigned short(根据int是否至少为unsigned int,它将被提升为intunsigned short许多值位为%d,因此%u%hu都可以。如果您愿意,可以自由使用{{1}}。

答案 2 :(得分:6)

从Linux手册页:

h      A  following  integer conversion corresponds to a short int or unsigned short int argument, or a fol‐
       lowing n conversion corresponds to a pointer to a short int argument.

因此,要打印无符号短整数,格式字符串应为"%hu"

答案 3 :(得分:2)

以下是Dim colRelBackup As Collection Set colRelBackup = DeleteRelationsGiveBackup("MyTable") 'Delete MyTable 'Import new version RestoreRelationBackup colRelBackup 说明符的good table。因此printf应为%hu

还有link to Wikipedia "C data types"