c – 像“1 $”这样的位置参数如何与printf()一起工作?

我找到了
printf("%*d",width,num);

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

是等同的

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

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

但是通过测试,似乎人是正确的;为什么?

解决方法

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 $标识其值被视为示例中的格式width – argument 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",num);.

如前所述,该标准将n $部分作为后缀修饰符(%和*),而不是作为格式转换说明符(在本示例中为d)和*的前缀修饰符.您的推定设计可能可以做出来,但不是选择的设计.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...