<分区>
在某些平台上,int32_t
(来自 stdint.h)是 long int
,但在其他平台上,它可能是 int
。当我想使用 printf
时,如何确定应该使用哪种格式,"%ld"
或 "%d"
?
或者,也许,我应该像下面这样强制将其转换为 long:
int32_t m;
m = 3;
printf ("%ld\n", (long)m);
但是这个解决方案很乏味。有什么建议吗?
<分区>
在某些平台上,int32_t
(来自 stdint.h)是 long int
,但在其他平台上,它可能是 int
。当我想使用 printf
时,如何确定应该使用哪种格式,"%ld"
或 "%d"
?
或者,也许,我应该像下面这样强制将其转换为 long:
int32_t m;
m = 3;
printf ("%ld\n", (long)m);
但是这个解决方案很乏味。有什么建议吗?
最佳答案
在 C 中(自 C99 起),inttypes.h
包含扩展为固定宽度类型的格式说明符的宏。对于 int32_t
:
printf("%" PRId32 "\n", m);
该宏很可能扩展为 "d"
或 "ld"
.您可以放置常用的修饰符等,例如:
printf("%03" PRId32 "\n", m);
在 C++(自 C++11 起)中,相同的功能可用于 #include <inttypes.h>
, 或 #include <cinttypes>
.
显然,某些 C++ 实现要求用户编写 #define __STDC_FORMAT_MACROS 1
之前#include <inttypes.h>
,即使 C++ 标准指定这不是必需的。
关于C++/C int32_t 和 printf 格式 : %d or %ld?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40121748/