使用 printf 格式在 C 中打印等宽列 [英] Print equal-width columns in C using printf formatting
问题描述
我想在 C 中使用 printf 打印列.我写了这个代码:
I would like to print columns using printf in C. I wrote this code:
#include <stdio.h>
void printme(char *txt1, char *txt2, char *txt3)
{
printf("TXT1: %9s TXT2 %9s TXT3 %9s\n", txt1, txt2, txt3);
}
int main()
{
printme("a","bbbbbbbeeeeebbbbb","e");
printme("aaaaaaaa","bbbbbbbbbbbb","abcde");
return 0;
}
它有效,但我有这样的输出:
It works but I have such output:
TXT1: a TXT2 bbbbbbbeeeeebbbbb TXT3 e
TXT1: aaaaaaaa TXT2 bbbbbbbbbbbb TXT3 abcde
所以列不是等宽的.基本上,我想这样做,无论我的论点中的文本有多长,我的函数都会始终打印出一个漂亮的格式化列.问题是:我该怎么做?
So the columns are not equal-width. Basicly, I would like to make it like this, that no matter how long is text in my argument, my function would ALWAYS print out a nice formatted columns. The question is: how can I do this?
说 nice 我的意思是无论我传递给打印函数多长的文本,它总是会打印出等宽的列,例如:
By saing nice I meant that no matter how long text I pass to my printing function, it will always print out equal-width columns, for example:
我的输出如下所示:
a cd` fg ij
a cd fg ij
a cd fg ij
ab cd fg ij
ab cd fg i j
ab cd fg ij
ab cd fg ij
ab cde fgh ij
ab cde fgh ij
我希望它看起来像这样(无论我的文本参数有多长):
I want it to look like this (no matter how long my text arguments will be):
a cd` fg ij
a cd fg ij
a cd fg ij
ab cd fg ij
ab cd fg ij
ab cd fg ij
ab cd fg ij
ab cde fgh ij
ab cde fgh ij
推荐答案
你可以找到txt1
、txt2
和txt3
,然后格式化:
You can find the maximum length for txt1
, txt2
, and txt3
, and then format it:
// compute the max string length of txt1 inputs in advance
int s1 = strlen(firstTxt1);
if (s1 < strlen(secondTxt1)
s1 = strlen(secondTxt1);
...
printf("%.*s %.*s %.*s\n", s1, txt1, s2, txt2, s3, txt3);
这篇关于使用 printf 格式在 C 中打印等宽列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!