What are printf() Flags and Examples Using Modifiers and Flags - C Language Basics

C examples for Language Basics:printf

Introduction

Flag Meaning
-The item is left-justified; that is, it is printed beginning at the left of the field. Example: "%-20s".
+Signed values are displayed with a plus sign, if positive, and with a minus sign, if negative. Example: "%+6.2f".
space Signed values are displayed with a leading space (but no sign) if positive and with a minus sign if negative. A + flag overrides a space. Example: "% 6.2f".
#Use an alternative form for the conversion specification. Examples: "%#o" , "%#8.0f" , and "%+#10.3E".
0For numeric forms, pad the field width with leading zeros instead of with spaces. Examples: "%010d" and "%08.3f".

Examples Using Modifiers and Flags

Demo Code


#include <stdio.h>
#define PAGES 959//from  w w w .  j  ava 2 s .  co  m

int main(void)
{
    printf("*%d*\n", PAGES);
    printf("*%2d*\n", PAGES);
    printf("*%10d*\n", PAGES);
    printf("*%-10d*\n", PAGES);
    
    return 0;
}

Result

some floating-point combinations

Demo Code

#include <stdio.h>

int main(void){
    const double RENT = 3852.99;  // const-style constant
    /*from   w  w  w.  ja  v a  2 s  .c o  m*/
    printf("*%f*\n", RENT);
    printf("*%e*\n", RENT);
    printf("*%4.2f*\n", RENT);
    printf("*%3.1f*\n", RENT);
    printf("*%10.3f*\n", RENT);
    printf("*%10.3E*\n", RENT);
    printf("*%+4.2f*\n", RENT);
    printf("*%010.2f*\n", RENT);
    
    return 0;
}

Result

illustrates some formatting flags

Demo Code

#include <stdio.h>
int main(void)
{
    printf("%x %X %#x\n", 31, 31, 31);
    printf("**%d**% d**% d**\n", 42, 42, -42);
    printf("**%5d**%5.3d**%05d**%05.3d**\n", 6, 6, 6, 6);
    //from   w  w  w .j a v a  2  s .  c  o m
    return 0;
}

Result

string formatting

Demo Code

#include <stdio.h>
#define BLURB "Authentic imitation!"
int main(void)
{
    printf("[%2s]\n", BLURB);
    printf("[%24s]\n", BLURB);
    printf("[%24.5s]\n", BLURB);
    printf("[%-24.5s]\n", BLURB);
    return 0;//from   w w w. ja  v  a  2  s .co  m
}

Result


Related Tutorials