如何用printf重复一个字符? [英] How to repeat a char using printf?
问题描述
我想要做类似的printf(?,计数,字符)
来重复一个字符计数
倍。
I'd like to do something like printf("?", count, char)
to repeat a character count
times.
什么是正确的格式字符串来完成呢?
What is the right format-string to accomplish this?
编辑:是的,很明显,我可以打电话给的printf()
在一个循环,但是这正是我想避免
Yes, it is obvious that I could call printf()
in a loop, but that is just what I wanted to avoid.
推荐答案
简短的回答 - 是的,长的答案:不是你想要的。
Short answer - yes, long answer: not how you want it.
您可以使用的printf 的%*的形式,它接受一个可变宽度。而且,如果你使用0作为你的价值进行打印,合并的与右对齐文本是零填充左侧。
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);
生产:
00000000000000000000
使用我的舌头牢牢地铭刻在了我的脸颊,我提供了code这个小恐怖表演片段。
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 <stdio.h>
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;
}
这篇关于如何用printf重复一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!