Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Using Flags in the printf function in C programming

September 30, 2013 Posted by: GPA Views: 26645 0 comments

Problem

How to format string using flags in C programming.

Solution

Function printf also has five flags that help to format output. Five flags are available in the table below.

Flag  Description

+ (plus sign)

Is used to display  "+" - positive values and a minus sign "-" values.
- (minus sign)
Left justify the output.
space (" ")
Print a space before a positive value.
# Is used with the octal conversion specifier o.
Is used with the hexadecimal conversion specifiers x or X.
0 (zero)
Is used to pad a field with leading zeros.

Example:



#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("globalproganswer.com\n\n");
printf("Demonstrates right justification:\n");
printf( "%5s%5d%5c%15f\n\n", "Peter", 8, 'b', 5.82 );
printf("Demonstrates left justification:\n");
printf( "%-5s%-5d%-5c%-5f\n", "John", 55, 'k', 2.47 );
printf("\nTest space flag:\n");
//The value -256 is not use a space in the output because of its minus sign.
printf("% d\n% d\n", 568, -256 );
printf("\nTest # flag:\n");
printf("%#o\n", 5848);
printf("%#x\n", 5848 );
printf("%#X\n", 5848 );
printf("\n%g\n", 5848.55 );
printf("%#g\n", 5848.55 );
printf("\nTest 0 (zero) flag:\n");
//add 4 zeros before value 696.
//Why 4? we have written "+08" + is the sing "+"
//then + 4 zeros + 6+9+6 total number of digits is 8 = +0000696
printf("%+08d\n",696);
//add 5 zeros before value 696 here no sign "+" that's why we have 5 zeros
printf("%08d\n",696);
system("PAUSE");
return 0;
}

Output

Flags

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe