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

前端之家收集整理的这篇文章主要介绍了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&C++相关文章