问题
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