-
Step 1
Understand that the printf function in C++ is kept in the cstdio library. You may need to include the stdio.h header file to use this function.
-
Step 2
Learn the syntax of printf. The complete syntax is int printf ( const char * format, ... ). This function takes character pointers as arguments and returns the number of characters written if the command is successful. Otherwise, printf returns a negative number.
-
Step 3
Know that the format may contain format tags using the following prototype: %[flags][width][.precision][length]specifier. Fields that are enclosed in brackets are optional. Note that the specifier is the only required component of the tag. The specifier must be one of the following: c (character); d or i (signed decimal integer);
e or E (Scientific notation using e or E); f (decimal floating point); g or G (use the shorter of %e/%E or %f); o (signed octal integer); s (character string); u (unsigned decimal integer); x (unsigned hexadecimal integer using lowercase letters); X (unsigned hexadecimal integer using uppercase letters); p (pointer); n (nothing printed) -
Step 4
Look at the following complete program for some simple examples of how to use printf:
#include
int main()
{
printf ("This format contains no specifiers.\n");
printf ("This format uses some characters: %c, %c, %c\n", 'a', 'b', 'c');
printf ("This format uses some decimals: %d, %d, %d\n", 1, 2, 3);
printf ("This format uses a string: %s, %s\n", "first string", "second string");
printf ("We will not use a new line character");
printf ("to print this line.");
return 0;
}
This program will give the following output:
This format contains no specifiers.
This format uses some characters: a, b, c
This format uses some decimals: 1, 2, 3
This format uses a string: first string, second string.
We will not use a new line character to print this line. -
Step 5
Note how the new line character ('\n') causes printf to output a new line. Otherwise, the next printf will output to the same line.










