Node:printf, Next:, Previous:Formatted string output, Up:Formatted string output



printf

If you have been reading the book closely up to this point, you have seen the use of the printf function many times. To recap, this function prints a text string to the terminal (or, to be more precise, the text stream stdout). For example, the following line of code prints the string Hello there!, followed by a newline character, to the console:

printf ("Hello there!\n");

You probably also remember that you can incorporate numeric constants and variables into your strings. Consider the following code example:

printf ("I'm free!  I'm free!  (So what?  I'm %d.)\n", 4);

The previous example is equivalent to the following one:

int age = 4;
printf ("I'm free!  I'm free!  (So what?  I'm %d.)\n", age);

Both of the code examples above produce the following output:

I'm free!  I'm free!  (So what?  I'm 4.)

You may recall that besides using %d with printf to print integers, we have also used %f on occasion to print floating-point numbers, and that on occasion we have used more than one argument. Consider this example:

printf ("I'm free!  I'm free!  (So what?  I'm %d.)  Well, I'm %f.\n", 4, 4.5);

That example produces the following output:

I'm free!  I'm free!  (So what?  I'm 4.)  Well, I'm 4.500000.

In fact, printf is a very flexible function. The general scheme is that you provide it with a format string or template string (such as "So what? I'm %d."), which can contain zero or more conversion specifications, conversion specifiers, or sometimes just conversions (in this case %d), and zero or more arguments (for example, 4). Each conversion specification is said to specify a conversion, that is, how to convert its corresponding argument into a printable string. After the template string, you supply one argument for each conversion specifier in the template string. The printf function then prints the template string, including each argument as converted to a printable sub-string by its conversion specifier, and returns an integer containing the number of characters printed, or a negative value if there was an error.