printf对齐

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
","1.1.1.1",24,"local ip");
  printf("%16s/%-10d %10s
","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
","1.1.1.1/24","local ip");
  printf("%-20s %-10s
","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"改成字符型的一个整体来排列。

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 01 02 03 04 05 06 07 08 09 10
1 . 1 . 1 . 1 / 2 4                     l o c a l   i p    
1 1 1 . 1 1 1 . 1 1 1 . 1 1 1 / 2 4     r e m o t e   i p  
原文地址:https://www.cnblogs.com/abc36725612/p/6235709.html