printing nice table

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Carramba

    printing nice table

    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!
  • Morris Dovey

    #2
    Re: printing nice table

    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



    Comment

    • Christopher Benson-Manica

      #3
      Re: printing nice table

      Morris Dovey <mrdovey@iedu.c omwrote:
      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)gma il.com | don't, I need to know. Flames welcome.

      Comment

      Working...