How to repeat a char using printf?

前端 未结 12 1080
难免孤独
难免孤独 2020-11-28 03:24

I\'d like to do something like printf(\"?\", count, char) to repeat a character count times.

What is the right format-string to accomplish

相关标签:
12条回答
  • 2020-11-28 04:23

    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.

    0 讨论(0)
  • 2020-11-28 04:25

    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);
    
    0 讨论(0)
  • 2020-11-28 04:27

    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.

    0 讨论(0)
  • 2020-11-28 04:27
    #include <stdio.h>
    #include <string.h>
    
    void repeat_char(unsigned int cnt, char ch) {
        char buffer[cnt + 1];
        /*assuming you want to repeat the c character 30 times*/
        memset(buffer,ch,cnd); buffer[cnt]='\0';
        printf("%s",buffer)
    }
    
    0 讨论(0)
  • 2020-11-28 04:29

    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

    #####
    
    0 讨论(0)
  • 2020-11-28 04:30

    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.

    0 讨论(0)
提交回复
热议问题