top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the purpose of using field width specifier in the printf() ?

+6 votes
840 views

How can we change the width in the printf() ? Can we also use negative width? What will be the impact of that?

posted Dec 21, 2013 by Prachi Agarwal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Tested the following code

main()
{
  printf("%5d\n", 1234%10);   
  printf("%5d\n", 1234%100);  
  printf("%d\n", 1234%10);   
  printf("%d\n", 1234%100);  
  printf("%-5d\n", 1234%10);   
  printf("%-5d\n", 1234%100);  
}

Output

    4
   34
4
34
4    
34   

So the interpretation is -
1. You can specify the field width just after % and output would be printed in a nice way as it was printed in the example using 5 spaces.
2. You can specify the negative width but would not have any impact.
3. In case of float you can specify the width after "." also.

Check the following article for complete detail on width specifier in printf.
http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output

answer Dec 21, 2013 by Anderson
...