C语言中,将printf函数打印出的字符像表格一样分类对齐。%-10d表示这个字符型占10个字节,负号表示左对齐。即下面表格中的x1位置开始填充。如果是%10d,表示右对齐,即在x10位置对齐。
x1 | x2 | x3 | x4 | x5 | x6 | x7 | x8 | x9 | x10 |
#include<stdio.h> int main(int argc,char **argv) { printf("%16s/%-10d %10s\n","1.1.1.1",24,"local ip"); printf("%16s/%-10d %10s\n","111.111.111.111",24,"remote ip"); return 0; }
运行结果
1.1.1.1/24 local ip 111.111.111.111/24 remote ip
上面例子中要实现两个printf打印的字符对齐,只能让字符都右对齐。如果要两行字符左对齐。代码修改如下
#include<stdio.h> int main(int argc,char **argv) { printf("%-20s %-10s\n","1.1.1.1/24","local ip"); printf("%-20s %-10s\n","111.111.111.111/24","remote ip"); return 0; }
运行结果
1.1.1.1/24 local ip 111.111.111.111/24 remote ip
也就是将"1.1.1.1/24"改成字符型的一个整体来排列。
原文:http://www.cnblogs.com/abc36725612/p/6235709.html