Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat a char using printf?

Tags:

c

printf

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.

like image 247
Maestro Avatar asked Feb 04 '13 00:02

Maestro


People also ask

How to print the same character multiple times in C?

C doesn't have any built-in way to repeat a character n times, but we can do it using the for loop.

What does %% mean in printf?

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.

What is a string C programming?

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.


2 Answers

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.

like image 125
rep_movsd Avatar answered Sep 22 '22 18:09

rep_movsd


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; } 
like image 26
synthesizerpatel Avatar answered Sep 18 '22 18:09

synthesizerpatel