C++ size_t 的正确 printf 格式说明符:%zu 或 %Iu?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15610053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct printf format specifier for size_t: %zu or %Iu?
提问by Patrick
I want to print out the value of a size_t
variable using printf
in C++ using Microsoft Visual Studio 2010 (I want to use printf
instead of <<
in this specific piece of code, so please no answers telling me I should use <<
instead).
我想在 C++ 中使用 Microsoft Visual Studio 2010打印出一个size_t
变量的值printf
(我想在这段特定的代码中使用printf
而不是使用<<
,所以请不要告诉我应该使用的答案<<
)。
According to the post
根据帖子
the correct platform-independent way is to use %zu
, but this does not seem to work in Visual Studio. The Visual Studio documentation at
与平台无关的正确方法是使用%zu
,但这在 Visual Studio 中似乎不起作用。Visual Studio 文档位于
http://msdn.microsoft.com/en-us/library/vstudio/tcxf1dw6.aspx
http://msdn.microsoft.com/en-us/library/vstudio/tcxf1dw6.aspx
tells me that I must use %Iu
(using uppercase i
, not lowercase l
).
告诉我必须使用%Iu
(使用大写i
,而不是小写l
)。
Is Microsoft not following the standards here? Or has the standard been changed since C99? Or is the standard different between C and C++ (which would seem very strange to me)?
微软不遵守这里的标准吗?还是自 C99 以来标准已更改?还是 C 和 C++ 之间的标准不同(这对我来说似乎很奇怪)?
采纳答案by Pavel P
MS Visual Studio didn't support %zu
printf specifier before VS2013
. Starting from VS2013 (e.g. _MSC_VER
>= 1800
) %zu
is available.
MS Visual Studio 之前不支持%zu
printf 说明符VS2013
。从 VS2013(例如_MSC_VER
>= 1800
)开始%zu
可用。
As an alternative, for previous versions of Visual Studio if you are printing small values (like number of elements from std containers) you can simply cast to an int
and use %d
:
作为替代方案,对于以前版本的 Visual Studio,如果您要打印小值(例如来自 std 容器的元素数),您可以简单地转换为 anint
并使用%d
:
printf("count: %d\n", (int)str.size()); // less digital ink spent
// or:
printf("count: %u\n", (unsigned)str.size());
回答by Orion Edwards
The Microsoft documentationstates:
Microsoft 文档指出:
The
hh
,j
,z
, andt
length prefixes are not supported.
在
hh
,j
,z
,和t
长度前缀不被支持。
And therefore %zu
is not supported.
因此%zu
不支持。
It also states that the correct prefix to use for size_t
is I
– so you'd use %Iu
.
它还指出要使用的正确前缀size_t
是I
– 所以你会使用%Iu
.
回答by Alexey Frunze
Microsoft's C compiler does not catch up with the latest C standards. It's basically a C89 compiler with some cherry-picked features from C99 (e.g. long long
). So, there should be no surprise that something isn't supported (%zu
appeared in C99).
Microsoft 的 C 编译器没有赶上最新的 C 标准。它基本上是一个 C89 编译器,具有一些来自 C99 的精选特性(例如long long
)。因此,不支持某些内容(%zu
出现在 C99 中)也就不足为奇了。