[英]Print equal-width columns in C using printf formatting
我想在C中使用printf打印列。我寫了這段代碼:
#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;
}
它有效,但我有這樣的輸出:
TXT1: a TXT2 bbbbbbbeeeeebbbbb TXT3 e
TXT1: aaaaaaaa TXT2 bbbbbbbbbbbb TXT3 abcde
所以列不是等寬的。 基本上,我想這樣做,無論我的論證中的文本有多長,我的函數總是打印出一個很好的格式化列。 問題是:我該怎么做?
saing nice我的意思是無論文本傳遞給我的打印功能多長時間,它都會打印出等寬列,例如:
我有這樣的輸出,如下所示:
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
我希望它看起來像這樣(無論我的文本參數多長時間):
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
如果您希望字符串在大於列寬時被截斷,那么您只需為字符串格式規范添加精度:
printf("TXT1: %9.9s TXT2 %9.9s TXT3 %9.9s\n", txt1, txt2, txt3);
使用printf()
,示例程序的輸出如下所示:
TXT1: a TXT2 bbbbbbbee TXT3 e
TXT1: aaaaaaaa TXT2 bbbbbbbbb TXT3 abcde
您可以找到txt1
, txt2
和txt3
的最大長度,然后對其進行格式化:
// 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);
不幸的是,沒有TRIVIAL方法可以做到這一點。
您可以在main()中執行兩遍方法:
char **data[] = { { "a","bbbbbbbeeeeebbbbb","e" },
{"aaaaaaaa","bbbbbbbbbbbb","abcde" } };
get_columwidths(data[0][0], data[0][1], data[0][2]);
get_columwidths(data[1][0], data[1][1], data[1][2]);
printme(data[0][0], data[0][1], data[0][2]);
printme(data[1][0], data[1][1], data[1][2]);
然后這個:
int columnwidths[3];
void get_columwidths(const char *s1, const char *s2, const char *s3)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
int len3 = strlen(s3);
if (columnwidths[0] < len1) columnwidths[0] = len1;
if (columnwidths[1] < len2) columnwidths[1] = len2;
if (columnwidths[2] < len3) columnwidths[2] = len3;
}
void printme(char *txt1, char *txt2, char *txt3)
{
printf("TXT1: %*s TXT2 %*s TXT3 %*s\n",
columnwidths[0], txt1, columnwidths[1], txt2, columnwidths[2], txt3);
}
看看我的簡單庫libtprint : https : //github.com/wizzard/libtprint代碼很簡單,你應該能夠理解它是如何工作的。
基本上你需要的是使用每列的字段寬度並計算對齊偏移。
希望能幫助到你 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.