ISO C99 printf (“%Nd”) 的前导零默认行为?

发布于 2024-12-31 22:39:17 字数 611 浏览 1 评论 0原文

我刚刚在 C99 ISO 标准 7.19.6.1 The fprintf function 第 6 小节中发现了以下内容,详细介绍了转换标志,特别是 0 标志:

0:d、i、o、u、x、X、a、A、e、E、f、F、g 和 G 转换,前导零(跟随任何符号指示)或基数)用于填充字段宽度而不是执行空间填充,除非转换无穷大或 NaN 时。

到目前为止一切顺利,我知道以下几行将产生所示的输出:

printf ("%5d\n", 7);   // produces "    7"
printf ("%05d\n",7);   // produces "00007"

但是,在详细介绍转换修饰符的第 8 小节中,我看到:

d,i: int 参数转换为带符号十进制,格式为 [−]dddd。精度指定出现的最小位数;如果要转换的值可以用更少的数字表示,则会用前导零进行扩展。

显然情况并非如此,因为默认行为是用空格而不是零填充。或者我在这里误读了什么?

I've just spotted the following in the C99 ISO standard, 7.19.6.1 The fprintf function, subsection 6, detailing the conversion flags, specifically the 0 flag:

0: d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, leading zeros (following any indication of sign or base) are used to pad to the field width rather than performing space padding, except when converting an infinity or NaN.

So far so good, I know that the following lines will produce the shown output:

printf ("%5d\n", 7);   // produces "    7"
printf ("%05d\n",7);   // produces "00007"

However, in subsection 8 detailing the conversion modifiers, I see:

d,i: The int argument is converted to signed decimal in the style [−]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros.

That's plainly not the case since the default behaviour is to pad with spaces, not zeroes. Or am I misreading something here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

溺ぐ爱和你が 2025-01-07 22:39:17

您混淆了精度字段宽度

printf("%.5i",  1);  // prints "00001", precision = 5
printf("%5i",   1);  // prints "    1", field width = 5
printf("%5.3i", 1);  // prints "  001", field width = 5, precision = 3

You're confusing precision and field width:

printf("%.5i",  1);  // prints "00001", precision = 5
printf("%5i",   1);  // prints "    1", field width = 5
printf("%5.3i", 1);  // prints "  001", field width = 5, precision = 3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文