By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,406 Members | 1,031 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,406 IT Pros & Developers. It's quick & easy.

printing nice table

P: n/a
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!
Jun 11 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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.

--
Morris Dovey
DeSoto Solar
DeSoto, Iowa USA
http://www.iedu.com/DeSoto/
Jun 11 '07 #2

P: n/a
Morris Dovey <mr*****@iedu.comwrote:
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.)

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Jun 11 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.