Maestro
Maestro

Reputation: 9518

How to repeat a char using 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.

Upvotes: 109

Views: 243391

Answers (14)

Neoheurist
Neoheurist

Reputation: 3484

Use Case:

Redaction: printing a fixed character for each character of a password string.

Macro:

Add this macro which prints a fixed character for each character of the string being redacted:

#define REDACT(___, _) for(char *__ = ___; *__; __++) putchar(_)

Usage:

Provide the string to be redacted and the redaction character to REDACT(,) as follows:

    char password[] = "secret";

    printf("Password: ");
    REDACT(password, '*');
    putchar('\n');

Output:

Password: ******

Note: _, __ and ___ within the REDACT(,) macro are valid C variable names, feel free to replace these with alphanumeric variable names to suit your development standards.

Upvotes: 0

rep_movsd
rep_movsd

Reputation: 6905

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.

[Edit]

Note that this format specifier will print a left substring of the input, so the number you use has to be <= the width of the string

Upvotes: 153

Pavlos Fragkiadoulakis
Pavlos Fragkiadoulakis

Reputation: 820

#include <stdio.h>
#include <string.h>

void repeat_char(unsigned int count, char ch) {
    char buffer[count + 1];
    memset(buffer, ch, count);
    buffer[count] = '\0';
    printf("%s", buffer)
}

Upvotes: 4

Murilo Perrone
Murilo Perrone

Reputation: 504

For best performance you could use memset then send that string directly to printf:

    char buffer[40];
    memset(buffer, '-', 39); // Set 39 characters
    buffer[39] = 0; // Tag the end of the string
    printf(buffer); // Print it

For instance, this method could be used to produce a rectangle of a given width and height:

#include <stdio.h>
 
int main() {
    int width = 40; // External width
    int height = 7; // External height

    char buffer[width + 2];
    memset(buffer, '-', width); // Set the dashes
    buffer[width] = '\n';  // Add carriage return
    buffer[width + 1] = 0; // Tag the end of string

    printf(buffer);

    char buffer2[width + 2];
    memset(buffer2 + 1, ' ', width - 2);
    buffer2[0] = '|';
    buffer2[width - 1] = '|';
    buffer2[width] = '\n';
    buffer2[width + 1] = 0;

    int l = height - 2;
    while (l-- > 0)
        printf(buffer2);

    printf(buffer);
    
    return 0;
}

Output:

----------------------------------------
|                                      |
|                                      |
|                                      |
|                                      |
|                                      |
----------------------------------------

Upvotes: 0

Charles
Charles

Reputation: 29

char buffer[41];

memset(buffer, '-', 40);    // initialize all with the '-' character<br /><br />
buffer[40] = 0;             // put a NULL at the end<br />

printf("%s\n", buffer);     // show 40 dashes<br />

Upvotes: 2

LoayH
LoayH

Reputation: 51

you can make a function that do this job and use it

#include <stdio.h>

void repeat (char input , int count )
{
    for (int i=0; i != count; i++ )
    {
        printf("%c", input);
    }
}

int main()
{
    repeat ('#', 5);
    return 0;
}

This will output

#####

Upvotes: 5

Ariel
Ariel

Reputation: 26783

If you limit yourself to repeating either a 0 or a space you can do:

For spaces:

printf("%*s", count, "");

For zeros:

printf("%0*d", count, 0);

Upvotes: 50

Rene
Rene

Reputation: 11

printf("%.*s\n",n,(char *) memset(buffer,c,n));

n <= sizeof(buffer) [ maybe also n < 2^16]

However the optimizer may change it to puts(buffer) and then the lack of EoS will .....

And the assumption is that memset is an assembler instruction (but still a loop be it on chip).

Strictly seen there is no solution given you precondition 'No loop'.

Upvotes: 1

ramon
ramon

Reputation: 900

If you have a compiler that supports the alloca() function, then this is possible solution (quite ugly though):

printf("%s", (char*)memset(memset(alloca(10), '\0', 10), 'x', 9));

It basically allocates 10 bytes on the stack which are filled with '\0' and then the first 9 bytes are filled with 'x'.

If you have a C99 compiler, then this might be a neater solution:

for (int i = 0;  i < 10;  i++, printf("%c", 'x'));

Upvotes: 8

synthesizerpatel
synthesizerpatel

Reputation: 28056

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;
}

Upvotes: 76

Kristian Gregersen
Kristian Gregersen

Reputation: 500

In c++ you could use std::string to get repeated character

printf("%s",std::string(count,char).c_str());

For example:

printf("%s",std::string(5,'a').c_str());

output:

aaaaa

Upvotes: 22

Keith Thompson
Keith Thompson

Reputation: 263647

printf doesn't do that -- and printf is overkill for printing a single character.

char c = '*';
int count = 42;
for (i = 0; i < count; i ++) {
    putchar(c);
}

Don't worry about this being inefficient; putchar() buffers its output, so it won't perform a physical output operation for each character unless it needs to.

Upvotes: 11

lindosekai
lindosekai

Reputation: 184

i think doing some like this.

void printchar(char c, int n){
     int i;
     for(i=0;i<n;i++)
         print("%c",c);
}

printchar("*",10);

Upvotes: -3

Mats Petersson
Mats Petersson

Reputation: 129524

There is no such thing. You'll have to either write a loop using printf or puts, or write a function that copies the string count times into a new string.

Upvotes: 16

Related Questions