Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print the same variable into a string several times?

Tags:

c

printf

I have a format string like this:

buf[] = "A%d,B%d,C%d,D%d,F%d,G%d,H%d,I%d,J%d";

and I want to insert the same integer for each %d so I use:

 int val = 6;
 sprintf(buf2, buf, val,val,val,val,val,val,val,val,val);

Can I use sprintf in a way that only requires me to write val once, and sprintf will use it for each %d?

like image 637
herzl shemuelian Avatar asked May 13 '12 13:05

herzl shemuelian


People also ask

How do you print a string many times?

The multiplication operator (*) prints a string multiple times in the same line. Multiplying a string with an integer n concatenates the string with itself n times. To print the strings multiple times in a new line, we can append the string with the newline character '\n'.

How do you write a string multiple times?

Use the Repetition Operator “*”: The elements of the string are repeated by the use of the “*” operation. In this instance, we declare a function named “repeat”. This function takes the values of words, “b” and “n” as arguments. The len() function is used to find out the length of the word.

How do I print a value multiple times in python?

Use the multiplication operator * to repeat a string multiple times. Multiply a string with the multiplication operator * by an integer n to concatenate the string with itself n times. Call print(value) with the resultant string as value to print it.


2 Answers

Yes, you can use %1$d everytime. The 1$ references the second argument, you could obviously do it with other arguments, too.

Demo: http://codepad.org/xVmdJkpN

Note that the position specifier is a POSIX extension - so it might not work with every single compiler. If you need it to work e.g. with the Visual C++ compiler, consider using the ugly way of repeating the argument or do not use a printf-style function at all. Another option would be using a POSIX-compatible sprintf implementation or using multiple calls to append one number everytime in a loop (in case the format string is built dynamically which would prevent you from specifying the correct number of arguments).


On a side-note, sprintf should be avoided. Use snprintf(buf2, sizeof(buf2), ....) instead. Of course this requires buf2 to have a static size known at compile-time - but if you allocate it manually you can simply use the variable containing the length instead of sizeof(buf2).

like image 128
ThiefMaster Avatar answered Oct 09 '22 05:10

ThiefMaster


There is no standard (i.e. portable) way of doing this.

like image 37
Oliver Charlesworth Avatar answered Oct 09 '22 05:10

Oliver Charlesworth