printing nice table

C

Carramba

Hello again!

I'm struggling with adjustment of print out table :)
I would like to have some thing like this execpt with right ajustment:

var1 some_var v next_var
_________________________________________
2 3 4 23.32


simple approach
#include <stdio.h>
#include <stdlib.h>

int main(void){

printf("%s\t%6s\t%6s\t%6s\n",
"var","next_var","v","more_v");
printf("%d\t%6.2f\t%6d\t%6.2f\t\n", 1333,96.00,11,0.12);
return 0;
}
/*output*/
var next_var v more_v
1333 96.00 11 0.12

dosn't work because I don't know in advance how large those variables
will by...
how would it by possible to make table for printout with fixed with
columns, and let header as well values to by right adjusted?


Thank you in advance!
 
M

Morris Dovey

Carramba wrote:

| dosn't work because I don't know in advance how large those
| variables will by...
| how would it by possible to make table for printout with fixed with
| columns, and let header as well values to by right adjusted?

You can either use pre-determined maximum field widths or you can make
two passes through the data, where the first pass is used to determine
the required field widths and the second does the actual output using
printf()'s '*' capability.
 
C

Christopher Benson-Manica

Morris Dovey said:
You can either use pre-determined maximum field widths or you can make
two passes through the data, where the first pass is used to determine
the required field widths and the second does the actual output using
printf()'s '*' capability.

It might be preferable to simply build the format string as
appropriate after the first pass and dispense with the '*'
functionality:

#include <stdio.h>
#include <string.h>

int main (int argc, const char *argv[]) {
int idx, fieldw=0;
char fmt[64]; /* Should dynamically allocate of course, but 64 is
enough here */
for( idx=1; idx < argc; idx++ ) {
if( strlen(argv[idx]) > fieldw ) {
fieldw=strlen( argv[idx] ); /* Could optimize and remove duplicate
strlen call() */
}
}
sprintf( fmt, "%%%ds\n", fieldw );
for( idx=1; idx < argc; idx++ ) {
printf( fmt, argv[idx] );
}
return 0;
}

(After some thought, maybe this isn't preferable, but it's an option.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top