Print equal-width columns in C using printf formatting -


i print columns using printf in c. wrote 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 have such output:

txt1:         txt2 bbbbbbbeeeeebbbbb txt3         e txt1:  aaaaaaaa txt2 bbbbbbbbbbbb txt3     abcde 

so columns not equal-width. basicly, make this, no matter how long text in argument, function print out nice formatted columns. question is: how can this?

by saing nice meant no matter how long text pass printing function, print out equal-width columns, example:

i have output looks this:

a         cd`           fg           ij           cd             fg           ij           cd             fg           ij   ab         cd             fg           ij   ab         cd             fg           j    ab         cd             fg           ij   ab         cd             fg           ij   ab         cde             fgh         ij   ab         cde             fgh         ij   

i want (no matter how long text arguments be):

a         cd`           fg           ij           cd            fg           ij           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     

you can find maximum length txt1, txt2, , txt3, , format it:

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

Comments