#1
  1. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363

    a variable width precision using printf


    I have a situation where I want to set a field width to be the size of the greatest input (length of char*).
    I know in c++ you can use setw manipulators and there is the %20s (or other number) for printf, but what if you dont know the width of the output until after the read, can you use a variable in the printf statement? Or am I confined to guessing the length?
    In case it helps, I am getting the length from the return value of getline.
  2. #2
  3. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2004
    Posts
    1,676
    Rep Power
    133
    There is * for field width or precision.
    Code:
    #include <stdio.h>
    
    int main(void)
    {
       const char text[] = "Hello world";
       int i;
       for ( i = 1; i < 12; ++i )
       {
          printf("\"%.*s\"\n", i, text);
       }
       return 0;
    }
    
    /* my output
    "H"
    "He"
    "Hel"
    "Hell"
    "Hello"
    "Hello "
    "Hello w"
    "Hello wo"
    "Hello wor"
    "Hello worl"
    "Hello world"
    */
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363
    Perfect, thank you.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    1
    Rep Power
    0

    Talking WOW!!! That is GRRRREAT!!!


    I have been writing code since the mid-70's (including lots of different assembly-languages), C since the early 80's, and yet I am always learning something new.

    This trick with specifying a width for a printf field using a variable is something I have never heard or seen before, but is exactly what I need for my current problem.

    THANKS A MILLION! WOW!!!!
    :D :o :D

IMN logo majestic logo threadwatch logo seochat tools logo