加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:37:59 所属栏目:百科 来源:网络整理
导读:我找到了 printf("%*d",width,num); 和 printf("%2$*1$d",num); 是等同的 但是IMO的第二种风格应该是一样的: printf("%*d",num,width); 但是通过测试,似乎人是正确的;为什么? 解决方法 printf() 的POSIX规范的相关部分定义了以下行为: Conversions can be
我找到了
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)和*的前缀修饰符.您的推定设计可能可以做出来,但不是选择的设计.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读