1. About.com
  2. Computing & Technology
  3. C / C++ / C#

Discuss in my forum

C Tutorial Lesson Two - Handling Numbers

By , About.com Guide

6 of 6

Learn how to use Format Specifiers
Format Specifiers can be enhanced with alignment, width and precision modifiers as -W.P W is the minimum field width in chars. P is the number of digits after the decimal point of a float, or number of digits of an int. A - means the output is left aligned, else it is right aligned.

Here are some examples.

#include <stdio.h>
int main() {
int a = 47;
int b = 218;
int c = 12345;
float f = 27.876;
double d = 27.876;

printf("Out %8d\n", a) ;
printf("Out %08d\n", a) ;
printf("Out %-8d\n", a) ;
printf("Out %-08d\n", a) ;

printf("Out %8d\n", b) ;
printf("Out %08d\n", b) ;
printf("Out %-8d\n", b) ;
printf("Out %-08d\n", b) ;

printf("Out %8d\n", c) ;
printf("Out %08d\n", c) ;
printf("Out %-8d\n", c) ;
printf("Out %-08d\n", c) ;

printf("Out %8.2e\n", f*f) ;
printf("Out %-8f\n", f) ;
printf("Out %-8.5f\n", f) ;
printf("Out %8f\n", f) ;

printf("Out %8.2e\n", d) ;
printf("Out %-8f\n", d) ;
printf("Out %-8.5f\n", d) ;
printf("Out %8f\n", d) ;
return 0; };

When run, this is the output

Out ......47
Out 00000047
Out 47
Out 47
Out .....218
Out 00000218
Out 218
Out 218
Out ...12345
Out 00012345
Out 12345
Out 12345
Out 2.79e+01
Out 27.875999
Out 27.87600
Out 27.875999
Out 2.79e+01
Out 27.876000
Out 27.87600
Out 27.876000
Notes periods are spaces. Note the loss of precision with the float variable f.

That completes this lesson. In lesson three, we'll start looking at chars and arrays.

©2012 About.com. All rights reserved. 

A part of The New York Times Company.