c - 打印一个参数两次

标签 c printf

我想将一个额外的参数传递给 printf 并打印两次,例如

printf("%s%s","somestring");       // prints somestringsomestring

有什么办法吗?

最佳答案

如果您使用的是 Linux 或其他类似 UNIX 的系统,则可以使用 $ 指定参数编号:

printf("%1$s%1$s\n", "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,

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

and

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

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.

关于c - 打印一个参数两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44192287/

相关文章:

c - MPI_Abort 和动态分配的内存

c - 将数组传递给函数会导致段错误(核心转储)

c - Arduino:printf/fprintf 打印问号而不是 float

c - 如何将参数传递给回调函数以创建新函数?

c - 如何为 macOS 构建可移植的静态 C 库

android - Android 中的 USB Dongle 识别 - Beaglebone

c - fprintf 在使用 Make 编译的 C 程序中不起作用

c - 使用多个变量时,如何通过 printf 函数删除 C 中多余的换行符?

c - 我如何让 printf 在 w32 上使用 'nan'?

c++ - char 数组存储太多字符? (c++)