C++ 使用 printf 打印 size_t 的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/940087/
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
What's the correct way to use printf to print a size_t?
提问by bradtgmurray
Size_t
is defined as an unsigned
integer, but the size of it depends on whether you're on a 32 or 64-bit machine. What's the correct and portable way to print out a size_t
?
Size_t
定义为unsigned
整数,但它的大小取决于您使用的是 32 位还是 64 位机器。打印输出的正确且便携的方法是size_t
什么?
回答by JaredPar
Try using the %zu
format string
尝试使用%zu
格式字符串
size_t val = get_the_value();
printf("%zu",val);
The z portion is a length specifier which says the argument will be size_t in length.
z 部分是一个长度说明符,表示参数的长度为 size_t。
Source - http://en.wikipedia.org/wiki/Printf#printf_format_placeholders
来源 - http://en.wikipedia.org/wiki/Printf#printf_format_placeholders
回答by David Thornley
There's a C++ tag on this, so cout <<
is another possible answer.
这里有一个 C++ 标签,所以cout <<
是另一个可能的答案。
This is surprisingly hard to get right in all versions of C. In C90, casting to unsigned long
should work, but that may well not work in C99, and the C99 solutions won't necessarily work in C90. The ability to reliably distinguish between C90 and C99 was introduced in the 1995 changes (specifying the allowable values for __STDC__
). I don't think there is a completely portable way that works for C90, C99, and C++, although there are solutions for any individual one of those.
在所有版本的 C 中都很难做到这一点。在 C90 中,强制转换unsigned long
应该可以工作,但这在 C99 中很可能不起作用,而且 C99 解决方案不一定在 C90 中工作。1995 年的更改中引入了可靠区分 C90 和 C99 的能力(指定 的允许值__STDC__
)。我不认为有一种完全可移植的方式适用于 C90、C99 和 C++,尽管有针对其中任何一个的解决方案。
回答by D.Shawley
I think that the C++ answer is:
我认为 C++ 的答案是:
std::size_t n = 1;
std::cout << n;
For C-style IO it's a little more complicated. In C99 they added the z
length modifier for size_t
values. However, previous to TR1 this is not supported so you are left with casting to a specific size like:
对于 C 风格的 IO,它有点复杂。在 C99 中,他们z
为size_t
值添加了长度修饰符。但是,在 TR1 之前,不支持此功能,因此您只能将其转换为特定大小,例如:
std::size_t n = 1;
std::printf("%lu\n", static_cast<unsigned long>(n));
Then again, unsigned long long
isn't really supported by C++ anyway so the above will work fine since unsigned long
is the largest legal integral type. After TR1 you can use %zu
safely for size_t
values.
再说一次,unsigned long long
无论如何 C++ 并没有真正支持,因此上述内容可以正常工作,因为unsigned long
它是最大的合法整数类型。在 TR1 之后,您可以%zu
安全地使用size_t
值。