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

printf两次参数

发布时间:2020-12-16 04:56:49 所属栏目:百科 来源:网络整理
导读:我想将一个额外的参数传递给printf并打印两次,例如 printf("%s%s","somestring"); // prints somestringsomestring 有没有办法做到这一点? 解决方法 如果您使用的是Linux或其他类似UNIX的系统,则可以使用$来指定参数编号: printf("%1$s%1$sn","hello");
我想将一个额外的参数传递给printf并打印两次,例如
printf("%s%s","somestring");       // prints somestringsomestring

有没有办法做到这一点?

解决方法

如果您使用的是Linux或其他类似UNIX的系统,则可以使用$来指定参数编号:
printf("%1$s%1$sn","hello");

在此示例中,1 $表示“使用第一个参数”.我们也多次使用这种语法,因此我们可以使用一次给定的参数.

Linux man page for printf提供了更多细节:

The arguments must correspond properly (after type promotion) with the
conversion specifier. By default,the arguments are used in the order
given,where each ‘*’ and each conversion specifier asks for the next
argument (and it is an error if insufficiently many arguments are
given). One can also specify explicitly which argument is taken,at
each place where an argument is required,by writing “%m$” instead of
‘%’ and “m$” instead of ‘‘,where the decimal integer m denotes the
position in the argument list of the desired argument,indexed
starting from 1. Thus,

06001

and

06002

are equivalent. The second style allows repeated references to the same argument. The C99 standard does not include the style using ‘$’,which comes from the Single UNIX Specification. If the style using ‘$’ is used,it must be used throughout for all conversions taking an argument and all width and precision arguments,but it may be mixed with “%%” formats which do not consume an argument. There may be no gaps in the numbers of arguments specified using ‘$’; for example,if arguments 1 and 3 are specified,argument 2 must also be specified somewhere in the format string.

(编辑:李大同)

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

    推荐文章
      热点阅读