微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)和*的前缀修饰符.您的推定设计可能可以做出来,但不是选择的设计.

原文地址:https://www.jb51.cc/c/114182.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐