How to repeat a char using printf?

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

    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'));
    

提交回复
热议问题