How to use format flags from printf to format data
Format data with printf
When using printf
to output string to the console we can format
value.
printf
format is a string argument followed by any additional arguments.
Flags for printf
.
- Width
- Precision
- Input size
- Type identifier
The general form of a placeholder is: % flags field-width precision prefix type-identifier.
printf() Type identifier
Conversion Character | Displays Argument (Variable's Contents) As |
---|---|
%c | Single character |
%d | Signed decimal integer (int) |
%e | Signed floating-point value in E notation |
%f | Signed floating-point value (float) |
%g | Signed value in %e or %f format, whichever is shorter |
%hd | (signed) short int |
%hu | unsigned short int |
%i | Signed decimal integer (int) |
%ld | (signed) long int |
%o | Unsigned octal (base 8) integer (int) |
%s | String of text |
%u | Unsigned decimal integer (int) |
%lu | unsigned long int |
%x | Unsigned hexadecimal (base 16) integer (int) |
The following code show show to use d
and i
converter.
#include <stdio.h>
/* w ww .j av a 2 s.com*/
main()
{
int i = 100;
printf(" %d\n",i);
printf(" %i\n",i);
}
The code above generates the following result.
Example
Output variable in various format
#include <stdio.h>
main()/*from w w w . jav a2 s . co m*/
{
int i = 100;
printf(" %c\n",i);
int j,k;
i = 6;
j = 8;
k = i + j;
printf("sum of two numbers is %d \n",k);
float f = 10.9999;
printf(" %e \n",f);
printf(" %E \n",f);
printf(" %f\n",f);
printf(" %g \n",f);
printf(" %G \n",f);
f = 10123456789.1234567899999;
printf(" %g \n",f);
printf(" %G \n",f);
i = 100;
printf(" %o\n",i);
printf(" %u\n",i);
printf(" %x\n",i);
printf(" %X\n",i);
char *i = "asdf\n";
printf(" %s\n",i);
}