I want to print a char '*'
repeatedly where I give the no. of times the asterisk should be repeated.
Example: count = 20
and I want to print ********************
using printf()
and format specifiers.
I want to print a char '*'
repeatedly where I give the no. of times the asterisk should be repeated.
Example: count = 20
and I want to print ********************
using printf()
and format specifiers.
There is certainly no way to achieve that using only format specifier. You could hide your loop in a macro maybe but you'll definitely need a loop somewhere.
You cannot do that with standard format specifiers provided by printf()
. However, there's a hacky solution (assuming the maximum padding length is reasonable), if you are willing to waste some space to store a filler string in your program.
#include <stdio.h>
int main(void) {
const char *fill = "********************"; // 20 chars
printf("%.*s\n", 10, fill);
printf("%.*s\n", 15, fill);
int n = 20;
printf("%.*s\n", n, fill);
return 0;
}
This works using .*
to provide the maximum length of the string to print as first parameter.
Output:
**********
***************
********************
NOTE: you will only get up to strlen(fill)
characters of padding (20 in the above example), anything more and printf
will stop at the \0
terminator of fill
.
I hope this is what you are looking for:
#include <stdio.h>
int main()
{
printf("%.*s", 20, "********************************");;
return 0;
}