Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf an argument twice

Tags:

c

printf

I want to pass one extra argument to printf and print it twice, e.g.

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

Is there any way to do this?

like image 425
DEADBEEF Avatar asked May 26 '17 01:05

DEADBEEF


People also ask

How do I print double in printf?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

Is %F for double?

"%f" is the (or at least one) correct format for a double. There is no format for a float , because if you attempt to pass a float to printf , it'll be promoted to double before printf receives it1.

How many arguments can printf take?

Printf can take as many arguments as you want. In the man page you can see a ... at the end, which stands for a var args. If you got 96 times %s in your first argument, you'll have 97 arguments (The first string + the 96 replaced strings ;) )

How do I printf a long double?

%Lf format specifier for long double %lf and %Lf plays different role in printf. So, we should use %Lf format specifier for printing a long double value.


1 Answers

If you are on Linux or some other UNIX like system, you can use $ to specify the argument number:

printf("%1$s%1$s\n", "hello");

In this example, 1$ means "use the first argument". We also use this syntax multiple times so we can use a given argument more that once.

The Linux man page for printf gives more details:

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.

like image 63
dbush Avatar answered Oct 04 '22 12:10

dbush