How to repeat a char using printf?

前端 未结 12 1209
难免孤独
难免孤独 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:11

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

提交回复
热议问题