www.thecareerplus.com
The CareerPlus
Home Technical Resources Programming Functions
Wednesday 08th September 2010
 
 
How can I have a variable field width with printf?

Discuss it!          


We can have a printf statement like :

printf("%*d", width, x);


Here is a C program to demonstrate this:


#include <stdio.h> 
#include <string.h> 

#define WIDTH 5 

int main ( void ) 
{ 
    char str1[] = "Good Boy"; 
    char str2[] = "The earth is round"; 

    int width = strlen ( str1 )  + WIDTH; 
    int prec  = strlen ( str2 )  + WIDTH; 

    printf ( "%*.*s\n", width, prec, str1 ); 
    return 0; 
}


Discuss it!          

CrackTheIntervew.NET
Advertisement
 
Top! Top!