C Format Specifiers

Format specifiers defines what type of data is to be printed or scanned. Consider format specifiers as a shoe; only a right kind foot can fit into it.

Format specifiers can be made to give or receive data in a restricted manner. Following are the three elements that can affect the behavior of the format specifiers.

  1. Minus (-): Specifies left alignment.
  2. Number after %: Specifies the minimum field width. If the width is less than the specified number then it will be padded by the spaces by the amount the string is lacking.
  3. Period (.): The period after % or number species the precision, i.e. number of digits after the decimal point.

List of Format Specifiers in C

Format Specifier Type Supported Data Type
%c Character char
unsigned char
%s String char *
%d Signed Integer int
short
unsigned short
long
%u Unsigned Integer unsigned int
unsigned long
%hi Signed Short Integer short
%hu Unsigned Short Integer unsigned short
%l or %ld or %li Signed Long Integer long
%lu Unsigned Long Integer unsigned int
unsigned long
%lli or %lld Signed Long Long Integer long long
%llu Unsigned Long Long Integer unsigned long long
%f Float float
%lf Double double
%Lf Long Double long double
%e or %E Floating Point in scientific notation float
double
%g or %G Floating Point in scientific notation, compares between %e and %f, whichever is shorter. float
double
%o Octal short
unsigned short
int
unsigned int
long
%x or %X Hexadecimal short
unsigned short
int
unsigned int
long
%p Prints address to which pointer refers void *
%n Prints nothing
%% Prints %

Format Specifiers C Demo

Code

#include<stdio.h>
int main(void)
{
    char s = 'X';
    char str[] = "Ten";
    int var = 10;
    float var2 = 10.0;
    
    printf("Character: %c\n",s);
    printf("String: %s\n",str);
    printf("Integer: %d\n",var);
    printf("Octal: %o\n",var);
    printf("Hexadecimal: %X\n",var);
    printf("Float: %f\n",var2);
    printf("Float in Scientific Notation: %e\n",var2);
    
    printf("\nXXXXXXXXXX\n"); //Ten X's
    printf("%5d\n",var);	  //padded left
    printf("%-5d\n",var);	  //padded right
    printf("%05d\n",var);	  //zero filled
    printf("%.2f\n",var2);    //Two digit precision
    printf("%10.2f\n",var2);  //Ten digit wide, two digit precision
    
    printf("\nPrints %%\n");
    printf("Prints %n\n");
    
    return 0;
}

Output

Character: X
String: Ten
Integer: 10
Octal: 12
Hexadecimal: A
Float: 10.000000
Float in Scientific Notation: 1.000000e+001

XXXXXXXXXX
   10
10
00010
10.00
     10.00

Prints %
Prints

Trending

C Programming

Remember to follow community guidelines and don't go off topic.