Using printf

The printf function was the standard way to produce output in C. C++ introduced cout and other ostreams, which have many advantages over the old system, but are distinctly less than perfect. Who can remember all the different manipulators?
The DISadvantages of printf are The ADvantages of printf are To use the printf function, your program must #include <stdio.h>. With some compilers you may #include <cstdio> instead, but not all compilers get everything right. If your program uses printf, it should not also use cout. Two different systems both trying to do the same kind of thing at the same time will sometimes cause output to be printed incorrectly, and occasionally some output may be lost completely. It is still OK to #include <iostream> and use the other things it provides (e.g. cin), but don't use both printf and cout in the same program.

General Form

The first parameter to printf is always a string. It specifies the format that the output should have by providing a picture of how it should look. After the format string, printf may be given any number of other parameters: these are the values that will be printed according to the format.

The basic operation of printf is simply to print out its format string, exactly as it appears, character by character. For example, this call:
          printf("Hello, how are you?\n");
simply prints:
          Hello, how are you?
followed by a newline character.

To make it useful, printf has an escape character: whenever it meets a percent sign % in its format string, it suspends the process of simply printing the string, and looks at the next few characters. These next few characters describe how a value is to be printed. The basic form of these format chracters is a percent sign followed by a single letter. printf simply takes the next parameter in turn, and prints it in the way the single letter demands, then gets back to the job of processing the rest of the format string. The most common format letters are d to indicate an int to be printed in decimal, x to indicate an int to be printed in hexadecimal, and f to indicate a float or double value to be printed in the normal way. Of course, there are many more.

Some simple examples:

This  

for (int i=1; i<7; i+=1)
  printf("%d cubed is %d\n", i, i*i*i);
  prints this  

1 cubed is 1
2 cubed is 8
3 cubed is 27
4 cubed is 64
5 cubed is 125
6 cubed is 216
This  

for (int i=1; i<7; i+=1)
  printf("The square root of %d is %f\n", i, sqrt(i));
  prints this  

The square root of 1 is 1.000000
The square root of 2 is 1.414214
The square root of 3 is 1.732051
The square root of 4 is 2.000000
The square root of 5 is 2.236068
The square root of 6 is 2.449490
This  

for (int i=3; i<1000000; i=i*9+2)
  printf("%d in hexadecimal is %x\n", i, i);
  prints this  

3 in hexadecimal is 3
29 in hexadecimal is 1d
263 in hexadecimal is 107
2369 in hexadecimal is 941
21323 in hexadecimal is 534b
191909 in hexadecimal is 2eda5

Complete list of useful format letters

 letter  parameter must be  how printed 
 c  int or char single character, by lookup in ASCII table, e.g. A for 65, 3 for 51.
 d  int or char in decimal
 e  float or double scientific notation, e.g. 1.23450e+02 for 123.45
 f  float or double the normal way
 o  int or char in octal (base 8)
 s  array of chars
or pointer to chars
as a string
 u  unsigned int
or unsigned char
in decimal
 x  int or char in hexadecimal (base 16) using as digits: 0123456789abcdef
 X  int or char in hexadecimal (base 16) using as digits: 0123456789ABCDEF
 %  (no parameter taken) a % sign is printed

Strings

Beware that the C++ type string did not exist in C. When C functions such as printf talk about strings, they mean arrays of characters. If you pass a C++ string to printf using the %s format, it will not work.

To use the %s format, you must pass printf an array of characters. This is in fact easy. In any program, when a string constant appears (for example "hello") in double quotes, it actually represents an array of characters, not a C++ string, so is perfectly OK for passing to printf. If you have a real C++ string in a variable, there is a simple conversion method: add .c_str() after the string variable's name, and an array-of-char equivalent will be produced, suitable for passing to printf.

Example:
        string avariable;
        avariable="hello";         // auto converted to a string
This is wrong wrong wrong:
        printf("%s", avariable);   // WRONG!!!!
But this is correct:
        printf("%s", avariable.c_str());   // Correct

Modifiers

using only the percent sign followed by a single letter, only a few basic formats can be acheived, but special modifiers may be inserted between the % and the format letter to make major changes to the way values are printed.

Some format modifiers produce extra spaces in the output. In all examples in this section, the underline character _ is used to indicate a space; none of the following examples actually produces an underline character in its output.

Minimum Width: A number may be added, to specify a minimum width for the entire value printed. Normally, only the characters required to correctly express the parameter's value are printed. If a minimum width is provided, and the number of characters printed would normally be less than that, extra spaces are printed before the value, producing right-justification and making it possible to align output in columns. Examples:
     printf("%d\n", 1234);   prints   1234
printf("%7d\n", 1234);   prints   ___1234
printf("%2d\n", 1234);   prints   1234
printf("sqrt(%d)=%f\n", 2, sqrt(2));   prints   sqrt(2)=1.414214
printf("sqrt(%d)=%12f\n", 2, sqrt(2));   prints   sqrt(2)=____1.414214
printf("*%s*\n", "hello");   prints   *hello*
printf("*%12s*\n", "hello");   prints   *_______hello*


Left Justification: Normally, if a minimum width specification forces extra spaces to be added, they are printed before the value, giving right justification. If a minus sign appears before the minimum width (making it appear negative), then any spaces will be added after the value instead.
     printf("%d\n", 1234);   prints   1234
printf("%7d\n", 1234);   prints   ___1234
printf("%-7d\n", 1234);   prints   1234___


Leading Zeros: Normally, if a minimum width specification forces extra characters to be added, they will be spaces. For numeric values, a zero may be put before the minimum width, in which case leading zeros will be printed instead of spaces.
     printf("%d\n", 1234);   prints   1234
printf("%07d\n", 1234);   prints   0001234
printf("%02d\n", 1234);   prints   1234
printf("%X\n", 1234);   prints   4D2
printf("%8X\n", 1234);   prints   _____4D2
printf("%08X\n", 1234);   prints   000004D2
printf("0x%08X\n", 1234);   prints   0x000004D2


Precision, or Maximum Width: A number may be added after a decimal point, to specify a precision for floating point numbers, or a maximum width for strings. It doesn't make much sense for integer values.
Float and double values are properly rounded to the specified number of decimal places. The format modifier .0 means no digits after the decimal point.
Minimum width and maximum width are often specified together.
     printf("sqrt(%d)=%f\n", 2, sqrt(2));   prints   sqrt(2)=1.414214
printf("sqrt(%d)=%.3f\n", 2, sqrt(2));   prints   sqrt(2)=1.414
printf("sqrt(%d)=%7.3f\n", 2, sqrt(2));   prints   sqrt(2)=__1.414
printf("*%s*\n", "abcdefghijklmn");   prints   *abcdefghijklmn*
printf("*%s*\n", "cat");   prints   *cat*
printf("*%8s*\n", "abcdefghijklmn");   prints   *abcdefghijklmn*
printf("*%8s*\n", "cat");   prints   *_____cat*
printf("*%.8s*\n", "abcdefghijklmn");   prints   *abcdefgh*
printf("*%.8s*\n", "cat");   prints   *cat*
printf("*%8.8s*\n", "abcdefghijklmn");   prints   *abcdefgh*
printf("*%8.8s*\n", "cat");   prints   *_____cat*


Forced Sign: Normally, if a value is negative, a minus sign is printed before it, but if a value is positive, no sign is printed. If a plus sign is inserted after the percent sign, a sign will always be printed for all values.
     printf("%d\n", 1234);   prints   1234
printf("%d\n", -1234);   prints   -1234
     printf("%+d\n", 1234);   prints   +1234
printf("%+d\n", -1234);   prints   -1234


Leave room for a Sign: Normally, if a value is negative, a minus sign is printed before it, but if a value is positive, no sign is printed. If a space is inserted after the percent sign, a space will be printed before any positive value, to help with alignment.
     printf("%d\n", 1234);   prints   1234
printf("%d\n", -1234);   prints   -1234
printf("% d\n", 1234);   prints   _1234
printf("% d\n", -1234);   prints   -1234


Rarely used special options: If a gish sign # appears after the percent sign, it produces an alternate form of output for some formats:

%#o: One leading zero is always printed

%#x and %#X: A leading 0x is always printed

%#e and %#f: A decimal point is always printed, even if no digits follow it.
     printf("%6.0f\n", 3.0);   prints   _____3
printf("%#6.0f\n", 3.0);   prints   ____3.
     printf("%o\n", 1234);   prints   2322
     printf("%#o\n", 1234);   prints   02322


Multiple Flags: The special characters +, -, (space), #, and 0 in formats may be used in any combination. They may appear in any order, immediately after the % sign.