【问题标题】:Left-pads the number with ` -` instead of spaces and 0 [duplicate]用`-`而不是空格和0来填充数字
【发布时间】:2013-09-11 00:05:30
【问题描述】:

当我们使用printf 时,我们可以这样写:

int i = 1;
printf("%06d" i);

然后我得到0000010 填充空间

那么有没有办法我可以使用其他字符(例如 -)而不是 0 来填充空间?

【问题讨论】:

标签: c printf


【解决方案1】:

这看起来不像是具有printf 系列功能的选项:您的选择有零'0' 或空格' '。如果必须用其他字符填充,则需要自己执行转换。

这样做的一种方法是使用sprintf 打印到带有空格填充的6 字符缓冲区,然后用破折号'-' 替换空格,如下所示:

char buf[12]; // 11 for the number plus one for the terminator
sprintf(buf, "%6d", i);
char *p = buf;
while (*p == ' ') {
    *p++ = '-';
}
printf("%s", buf);

【讨论】:

  • 谢谢,我只想知道有没有捷径。 :)
  • buf[7] 应该更大,因为%6d 不限制打印的字符数,只指定最小值。
  • 我正在处理stackoverflow.com/questions/18708679/…中的最佳尺寸问题
猜你喜欢
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
相关资源
最近更新 更多