我有以下程序
#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
并且在使用长度修饰符(例如short
,long
等)与unsigned
进行{int
时无法理解正确的格式说明符{1}}数据类型。
%u
是正确的说明符unsigned short int
吗?如果是这样,为什么我得到上述警告?!
编辑:
大多数时候,我正在尝试%uh
并且它仍在发出警告。
答案 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
,它将被提升为int
或unsigned 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
。