Shift Loader Shift Loader - 2 months ago 11
C Question

How can I print multiple character with one printf?

I want to print multiple character using

printf
. My approach up to now is this-

#include <stdio.h>

int main()
{
printf("%*c\n", 10, '#');

return 0;
}


But this only prints 9 spaces before the
#
.

I want to print it like this-

##########


I am unable to figure out how to do this. Please help me?

Answer

You can not use printf like that to print repetitive characters in Ansi C. I suggest you to use a loop like this -

#include <stdio.h>

int main()
{
    int i;
    for(i = 0; i < 10; i++) putchar('#');

    return 0;
}

Or if you have absolutely no desire to use loops, you can do something like this-

#include <stdio.h>
int main()
{
    char out[100];
    memset(out, '#', 10);
    out[10] = 0;
    printf("%s", out);

    return 0;
}

By the way, using printf like this also works-

#include <stdio.h>

int main()
{
    printf("%.*s", 10, "############################################");

    return 0;
}
Comments