我试图以更漂亮的方式打印我的代码,但我不确定如何解决我的问题......
Protein: Donations:0 Requests: 0
Dairy: Donations:0 Requests: 0
Grains: Donations:0 Requests: 0
Vegetables: Donations:0 Requests: 0
Fruits: Donations:0 Requests: 0
这是我对print语句的代码:
printf("%s:\tDonations:%d Requests: %d\n", TYPES[i], status[0][i], status[1][i]);
我希望它看起来像这样:
Protein: Donations:0 Requests: 0
Dairy: Donations:0 Requests: 0
Grains: Donations:0 Requests: 0
Vegetables: Donations:0 Requests: 0
Fruits: Donations:0 Requests: 0
有什么想法吗?
答案 0 :(得分:3)
诀窍是打印冒号后面有正确数量的空格。您可以通过利用printf
提供的多项功能来实现此目的:
printf
返回打印的字符数printf
可以在最小字段宽度中保留对齐文本,例如在格式字符串"%-10s"
中,减号导致文本左对齐,数字10
指定最小字段宽度为10. printf( "%-*s", 10, "hello" )
将打印"hello"
后跟5个空格总而言之,代码看起来像这样:
int count = printf( "%s", TYPES[i] );
printf( "%-*s", 16-count, ":" );
printf( "Donations:%2d Requests:%2d\n", status[0][i], status[1][i] );