Thread: How to printf for varying variable

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    5

    How to printf for varying variable

    I am trying to pad result with a length of zeros specified by padlength,
    I'm unsure of how to do this since the printf doesn't take this arg..


    Code:
    
    void printConversion(int value)
    {
    	char *result = convert(value);
    	int padLength = 12-strlen(result);
    
    	printf("%d ",value);
    	printf("%0padLengths\n",result);
    }
    
    
    
    char *convert(int value)
    {
    	static char buf[5];
    	itoa(value, buf, 2);
    	return buf;
    }

  2. #2
    Awesomefaceradcore bivhitscar's Avatar
    Join Date
    Apr 2006
    Location
    Melbourne, Australia
    Posts
    210
    The easiest way to do it would be a loop.
    Code:
    for ( i = 0; i < padLength; i++ )
    {
        printf("0");
    }
    it's ironic considerate rarity patron of love higher knowledge engulfs me...

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Maybe something like this?
    Code:
    void printConversion(int value)
    {
    	char *result = convert(value);
    	int padLength = 12-strlen(result);
    
    	printf("%10d ",value);
    	printf("%0*d%s\n", padLength, 0, result);
    }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with a C Programing Quiz project
    By dilemma in forum C Programming
    Replies: 12
    Last Post: 05-15-2009, 03:35 PM
  2. I have some questions :(
    By geekrockergal in forum C Programming
    Replies: 19
    Last Post: 02-01-2009, 09:44 AM
  3. saying hello and 1st question
    By darksys in forum C Programming
    Replies: 12
    Last Post: 10-31-2008, 02:58 PM
  4. Newb Help: Full Arrays and Functions
    By LycanGalen in forum C Programming
    Replies: 5
    Last Post: 01-31-2008, 08:35 PM
  5. Double to Int conversion warning
    By wiznant in forum C Programming
    Replies: 15
    Last Post: 09-19-2005, 09:25 PM