使用printf格式在C中打印等宽列

时间:2013-07-19 17:11:19

标签: c printf

我想在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    

4 个答案:

答案 0 :(得分:10)

如果你想要将字符串大于列宽来截断字符串,那么你只需为字符串格式规范添加一个精度:

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

答案 1 :(得分:4)

您可以找到txt1txt2txt3的最大长度,然后对其进行格式化:

// 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);

答案 2 :(得分:3)

不幸的是,没有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);
}

答案 3 :(得分:2)

看看我的简单图书馆libtprinthttps://github.com/wizzard/libtprint 代码很简单,你应该能够理解它是如何工作的。

基本上你需要的是使用每列的字段宽度并计算对齐偏移。

希望它有所帮助!

相关问题