C printf field width

Description

Field-width sets the least number of columns for output.

Example

add field width for int type output


#include <stdio.h>
/* ww w  . ja va 2 s  .c o m*/
main()
{
    int i = 9;
    printf(">%4d<",i);
}

The code above generates the following result.

Example 2

If the value is more than the specified column, field-width is ignored.


#include <stdio.h>
main()//from w w w.j av a  2 s. c o m
{
    int i = 999999;
    printf(">%4d<",i);
}

The code above generates the following result.

Example 3

Flag characters are used to give directives for the output. You can use multiple flag characters in any order. - Indicates that output is left justified.


#include <stdio.h>
//from   w  w  w .  j av a  2  s .  com
main()
{
    printf("%-10.4d\n", 25);
    printf("%10.4d\n", 25);
}

Example 4

Right justifying and left justifying values


#include <stdio.h>
// w ww  .j av  a2s.c  om
int main()
{ 
   printf( "%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23 );
   printf( "%-10s%-10d%-10c%-10f\n", "hello", 7, 'a', 1.23 );

   return 0;

}

The code above generates the following result.

Example 5

control field width for float point value


#include <stdio.h>
/* www . j  a v  a 2s. c o  m*/
int main(void)
{
  double item;

  item = 10.12304;

  printf("%f\n", item);
  printf("%10f\n", item);
  printf("%012f\n", item);

  return 0;
}




















Home »
  C Language »
    Input / Output »




printf
scanf