在linux-terminal中用c打印漂亮的表

时间:2015-06-28 16:43:57

标签: c printf

我为学生写了一个小数据库。从终端获取数据后,我想在漂亮的表中打印这些数据。该表看起来像:

lastname|firstname|enrollement nr|subject|nationality. 

但我无法打印整行数据。这意味着如果我想打印一个学生的信息,数据将分为两行。表格的标题将不会拆分,但表格的每一行都将被拆分。这是代码:

 void display_db(){
    printf("lastname|firstname|enrollement nr|subject   |nationality\n");
    printf("========================================================\n");
    int i;
    for(i=0;i<SIZE;i++){
         printf("%10s|%10s|%10d|%10s|%10s\n",           
             (db+i)->lastname,(db+i)->firstname,(db+i)->mNr,   (db+i)->subject, (db+i)->nationality);
    }
 }

这是一张图片:

enter image description here

删除特殊字符'\ n'后,我修改了打印表格的代码。桌子现在漂亮了。这是代码:

void display_db(){
printf("%10s|%10s|%10s|%30s|%10s\n","lastname","firstname","enroll. nr","subject","nationality");
printf("========================================================\n");
int i;
for(i=0;i<SIZE;i++){
printf("%10s|%10s|%10d|%30s|%10s\n",            
        (db+i)->lastname,(db+i)->firstname,(db+i)->mNr, (db+i)->subject, (db+i)->nationality);
}

}

1 个答案:

答案 0 :(得分:2)

从struct元素中删除尾随换行符

size_t element_len = strlen(element);
if (element_len && (element[element_len - 1] == '\n')) {
    element[--element_len] = 0; // remove trailing newline and update element_len
}