Centering strings with printf()

前端 未结 7 1181
挽巷
挽巷 2020-12-01 10:33

By default, printf() seems to align strings to the right.

printf(\"%10s %20s %20s\\n\", \"col1\", \"col2\", \"col3\");
/*       col1                     


        
相关标签:
7条回答
  • 2020-12-01 11:32

    You can use either of the following two options:

    char name[] = "Name1";
    
    //Option One
    printf("%*s", 40+strlen(name)/2, name, 40-strlen(name)/2, "");
    puts("");//skip one line
    
    //Option two
    printf("%*s", 40+strlen("Name2")/2, "Name2", 40-strlen("Name2")/2, "");
    

    The output is:

    Name1(center)
    Name2(center)

    0 讨论(0)
提交回复
热议问题