如果我有一个整数变量,我可以使用以下所示的格式说明符%d来使用sscanf
。
sscanf (line, "Value of integer: %d\n", &my_integer);
我在哪里可以找到uint8_t
、uint16_t
、uint32_t
和uint64_t
的格式说明符?
uint64_t
可能有 %lu。
它们在<inttypes.h>
中声明为宏:SCNd8、SCNd16、SCNd32和SCNd64。
例如(针对int32_t):
sscanf (line, "Value of integer: %" SCNd32 "\n", &my_integer);
uint32_t
应使用 SCNu32
,而 int32_t
应使用 SCNi32
。 - Sander De Dycker<inttypes.h>
存在,在第二种情况下,假设我知道的实现同时导入了<inttypes.h>
和<stdint.h>
,这是一个相当安全的打赌。 - AProgrammerscanf()
格式中的结尾 '\n'
会带来一些问题。 - chux - Reinstate Monica如其他人所说,需要包含定义格式宏的<stdint.h>
头文件。但在C ++中,在包含它之前请先定义__STDC_FORMAT_MACROS
。从stdint.h:
/* The ISO C99 standard specifies that these macros must only be
defined if explicitly requested. */
#if !defined __cplusplus || defined __STDC_FORMAT_MACROS
<any_type> x;
f >> x;
并完成。例如:
std::stringstream ss;
uint32_t u;
std::cin >> u;
,然后用
sscanf作为
fscanf`的替代方案。 - Sebastian Mach读取 uint64_t
(typedef unsigned long long int)的正确格式是使用 scanf
而不是 sscanf
,格式为 "%" SCNu64
,打印同样也是使用 SCNu64
。
例如,在您的代码中,您读取了变量 my_integer,然后执行以下操作:
scanf ("Value of integer:%" SCNu64, & my_integer);
,如果要使用 printf 输出相同的内容,则可以这样写。
<inttypes.h>
,格式如SCNX8、SCNd16。<inttypes.h>
与<stdint.h>
(声明了int8_t
等typedef)同时被引入,正式地出现在C++0X中,但在实践中作为扩展在与C99实现有强关联的实现中可用。 - AProgrammer你可以在C++中的<cstdint>
或者C中的<types.h>
中检查类型。然后你可以指定当前编译在你的机器上的格式。
如果变量是unsigned
,那么你需要使用%u
,如果变量是signed
,那么使用%d
。对于小于32字节的变量大小,你不需要指定长前缀。
在我的配置中,我有一个64位程序,所以我的uint64_t
被编译为unsigned long long int
,所以意味着要使用%llu
。如果你的程序将在32位编译,你可以使用%lu
,因为uint64_t
将被编译为unsigned long int
但是还有谁在使用x86呢?:)
uint8_t, uint16_t, uint32_t - %u
uint64_t - %llu
int8_t, int16_t, int32_t - %d
int64_t -%lld
%lu
不是用于unsigned long
吗?通常是 32 位。 - MSaltersunsigned long
在所有的 64 位 UNIX 变种系统上并不是 64 位。在使用 GCC 的 64 位 Solaris 上它是32位的。我曾经有一次非常痛苦的经历,因为我学到它在 Linux 上是64位的。 - camelccc