Tuesday, January 27, 2015

Format Specifiers in C

Let us take a look at some format specifiers used in printf which are necessary to format the output.....

%x--> prints an int in hexadecimal.
%4x--> prints a hex int, right-justified to 4 places. If it's less than 4 digits, it's preceded by spaces. If it's more than 4 digits, you get the full number.
%04x--> prints a hex int, right-justified to 4 places. If it's less than 4 digits, it's preceded by zeroes. If it's more than 4 digits, you get the full number, but no leading zeroes.

example:
void main()
{
int i=98;
printf("%x\n",i);
printf("%4x\n",i);
printf("%04x",i);
getch();
}

output:
62
       62
00062

Similary with %d
void main()
{
int i=5;
printf("%d\n",i);
printf("%4d\n",i);
printf("%04d",i);
getch();
}

output:
5
         5
00005

Similary with %c..
 void main()
{
char c='a';
printf("%c\n",c);
printf("%4c\n",c);
printf("%04c",c);
getch();
}


output:
a
         a

0000a