Have a value be printed with a varying number of spaces before it?

不想你离开。 提交于 2021-02-10 18:38:46

问题


Is this possible? So if I were to print a value, I could print it with, say, 3 spaces before the actual output instead of four?


回答1:


printf has a * format for dynamically specifying a minimum field width:

#include <stdio.h>
int main(int argc, char *argv[])
{
    int value = 5;
    const char *name = "LaDonna";
    double value2 = 200.55;
    const char *space = " ";
    for (int width = 0; width < 10; width++)
        printf("%*d %*.2f %*s\n",width,value,width,value2,width + 5,name);
    for (int width=1; width < 5; width++)
        printf("%*s%d\n",width,space,width);
    return 0;
}

outputs:

5 200.55 LaDonna
5 200.55 LaDonna
 5 200.55 LaDonna
  5 200.55  LaDonna
   5 200.55   LaDonna
    5 200.55    LaDonna
     5 200.55     LaDonna
      5  200.55      LaDonna
       5   200.55       LaDonna
        5    200.55        LaDonna
 1
  2
   3
    4


来源:https://stackoverflow.com/questions/12450853/have-a-value-be-printed-with-a-varying-number-of-spaces-before-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!