Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print multiple character with one printf?

Tags:

c

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?

like image 623
Shift Loader Avatar asked Aug 31 '15 16:08

Shift Loader


People also ask

How do you print %% in printf?

To print a percent-sign character, use %%. For non decimal floating-point numbers, signed value having the form [-]0xh. hhhhp[sign]ddd, where h is a single hexadecimal digit, hhhh is one or more hexadecimal digits, ddd is one or more decimal digits, and sign is + or -.

Can we multiply char in C?

No, you can't do this in 'C' as far as I think.In python multiplication of a string by a number is defined as 'repetition' of the string that number of times. One way you can do this in 'C++'(a superset of 'C' language) is through 'operator overloading'.

How do I print a character in printf?

Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use '%%'. Neither single % will print anything nor it will show any error or warning.

What is %s in printf?

%s and string We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.


2 Answers

I think the best approach, if you have an upper limit to the number of characters to be output is:

printf("%.*s", number_of_asterisks_to_be_printed,
"**********************************************************************");

I think this will also be the most efficient, portable way to do that.

like image 140
Luis Colorado Avatar answered Sep 28 '22 07:09

Luis Colorado


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;
}
like image 39
Dipu Avatar answered Sep 28 '22 07:09

Dipu