Thread: left justification using printf

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    1

    left justification using printf

    I am trying to print a string of different data types, and my second column needs to be left justified. My code looks like:

    printf("%15d%-3d", variable, name)

    The second column keeps running into the first, so instead of columns like this:
    1 7
    23 16
    450 125

    they look like this:

    17
    2316
    450125

    If anyone has any ideas on how I can fix my formatting, problem, I would really appreciate help. Thanks.

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    It shouldn't be "%-3d". Also add "\n" and ";". This works fine with me:

    printf("%15d%15d\n", variable, name);

  3. #3
    Registered User biosx's Avatar
    Join Date
    Aug 2001
    Posts
    230
    Here is some code that might help you figure it out:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
    
    	int num1 = 10,
    	     num2 = 20,
    	     num3 = 110,
    	     num4 = 2250,
    	     num5 = 23,
    	     num6 = 23505,
    	     num7 = 2,
    	     num8 = 102;
    
    	printf("%-15d %-15d\n", num1, num2);
    	printf("%-15d %-15d\n", num3, num4);
    	printf("%-15d %-15d\n", num5, num6);
    	printf("%-15d %-15d\n", num7, num8);
    
    	return 0;
    }
    The idea is to think of the maximum number of characters (or spaces) that a number will take up. So let's say the maximum number of characters an input value will be is 5 characters. To make it look nice you might want to add some padding on to that (1 or 2 spaces). Then you code it out:

    printf("%-5d %-5d %-5d\n", num1, num2, num3); // 3 columns, 1 space padding

    Hope that helps
    Hope that helps
    Last edited by biosx; 02-19-2002 at 07:54 PM.

  4. #4
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    Code:
    printf("%15d%2s%-3d", variable," ", name);
    You can also use empties!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. making it portable.....?
    By ShadeS_07 in forum C Programming
    Replies: 11
    Last Post: 12-24-2008, 09:38 AM
  2. saying hello and 1st question
    By darksys in forum C Programming
    Replies: 12
    Last Post: 10-31-2008, 02:58 PM
  3. Newb Help: Full Arrays and Functions
    By LycanGalen in forum C Programming
    Replies: 5
    Last Post: 01-31-2008, 08:35 PM
  4. menu problem!!! need U R G E N T help!!!
    By catcat28 in forum C Programming
    Replies: 16
    Last Post: 11-19-2007, 01:32 PM
  5. Whats Wrong Whith This!?
    By SmokingMonkey in forum C++ Programming
    Replies: 8
    Last Post: 06-01-2003, 09:42 PM