You are here:About>Computing & Technology>C / C++ / C#> C> C Tutorials> Modifying format Specifiers
About.comC / C++ / C#

C Tutorial Lesson Two - Handling Numbers

From David Bolton,
Your Guide to C / C++ / C#.
FREE Newsletter. Sign Up Now!

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.

  1. All About Numbers in C
  2. More About Ints
  3. Precision Arithmetic
  4. Learn about Arithmetic Operations
  5. Specifying Output Formats in Printf
  6. Learn how to use Format Specifiers

<< Previous | Next

 All Topics | Email Article | Print this Page | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.