Thread: Free space in printf

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    48

    Free space in printf

    Hello

    Is it possible to have an amount of free space before something gets printed?

    like:

    printf("Cost $%lf", cost)
    the cost is sometimes 2 digits or 4 digits depending on which option the user has selected, and since there are more than 1 printf they don't always align. Is there a way to have them align even if the numbers area different at different times?


    Thanks

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Code:
    printf("Cost $%4lf", cost);

  3. #3
    Registered User
    Join Date
    Oct 2007
    Posts
    48
    That worked but the Dollar sign stays all the way at the beginning at the price gets printed with the space. Is there anyway to make the dollar sign move with it too?

    Thanks

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    903
    Code:
    char* output = cost >= 100 ? "Cost $%4lf" : "Cost $%2lf";
    printf(output, cost);

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    sprintf(temp,"$%f", cost );
    printf("Cost %4s", temp );

    There's no such format as %lf, it's just %f for floats and doubles.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    %lf is supported by extension I believe in some compilers. It's real usage, however, is for the scanf() family of functions.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems reading entered race times C
    By loopymoo26 in forum C Programming
    Replies: 12
    Last Post: 05-23-2009, 07:38 AM
  2. I need help on this particular Linked List problem
    By sangken in forum C Programming
    Replies: 11
    Last Post: 08-06-2006, 12:26 AM
  3. Help needed with backtracking
    By sjalesho in forum C Programming
    Replies: 1
    Last Post: 11-09-2003, 06:28 PM
  4. someone who is good at finding and fixing bugs?
    By elfjuice in forum C++ Programming
    Replies: 8
    Last Post: 06-07-2002, 03:59 PM