gpt4 book ai didi

c - 像 "1$"这样的位置参数如何与 printf() 一起使用?

转载 作者:太空狗 更新时间:2023-10-29 16:33:34 25 4
gpt4 key购买 nike

通过 man 我找到了

               printf("%*d", width, num);

               printf("%2$*1$d", width, num);

是等价的。

但是 IMO 第二种样式应该是一样的:

               printf("%*d", num, width);

但是通过测试看来 man 是对的;为什么?

最佳答案

printf()的POSIX规范的相关部分定义此行为:

Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier character % (see below) is replaced by the sequence "%n$", where n is a decimal integer in the range [1,{NL_ARGMAX}], giving the position of the argument in the argument list. This feature provides for the definition of format strings that select arguments in an order appropriate to specific languages (see the EXAMPLES section).

The format can contain either numbered argument conversion specifications (that is, "%n$" and "*m$"), or unnumbered argument conversion specifications (that is, % and * ), but not both. The only exception to this is that %% can be mixed with the "%n$" form. The results of mixing numbered and unnumbered argument specifications in a format string are undefined. When numbered argument specifications are used, specifying the Nth argument requires that all the leading arguments, from the first to the (N-1)th, are specified in the format string.

In format strings containing the "%n$" form of conversion specification, numbered arguments in the argument list can be referenced from the format string as many times as required.

%n$ 标识要打印其值的参数 - 在您的示例中为参数 2。

*n$ 标识其值将被视为格式宽度的参数 - 在您的示例中为参数 1。

因此,编写手册的人员遵循了标准。


你在评论中争论:

2$* should match the 2nd parameter while 1$d should match the first one, but it turns out that it's not true in the case of printf("%2$*1$d", width, num);.

如前所述,该标准明确将 n$ 部分附加为 %* 的后缀修饰符,而不是作为格式转换说明符(本例中为 d)和 *。您假定的设计可能会起作用,但不是所选择的设计。

关于c - 像 "1$"这样的位置参数如何与 printf() 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6322540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com