I'd like to do something like printf("?", count, char)
to repeat a character count
times.
What is the right format-string to accomplish this?
EDIT: Yes, it is obvious that I could call printf()
in a loop, but that is just what I wanted to avoid.
C doesn't have any built-in way to repeat a character n times, but we can do it using the for loop.
As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.
In C programming, a string is a sequence of characters terminated with a null character \0 . For example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.
You can use the following technique:
printf("%.*s", 5, "=================");
This will print "====="
It works for me on Visual Studio, no reason it shouldn't work on all C compilers.
Short answer - yes, long answer: not how you want it.
You can use the %* form of printf, which accepts a variable width. And, if you use '0' as your value to print, combined with the right-aligned text that's zero padded on the left..
printf("%0*d\n", 20, 0);
produces:
00000000000000000000
With my tongue firmly planted in my cheek, I offer up this little horror-show snippet of code.
Some times you just gotta do things badly to remember why you try so hard the rest of the time.
#include <stdio.h> int width = 20; char buf[4096]; void subst(char *s, char from, char to) { while (*s == from) *s++ = to; } int main() { sprintf(buf, "%0*d", width, 0); subst(buf, '0', '-'); printf("%s\n", buf); return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With