Sams Teach Yourself C in 21 Days

(singke) #1
Theprintf()function takes a variable number of arguments, with a minimum of one.
The first and only required argument is the format string, which tells printf()how to
format the output. The optional arguments are variables and expressions whose values
you want to display. Take a look at these few simple examples, which give you a feel for
printf(), before you really get into the nitty-gritty:


  • The statement printf(“Hello, world.”);displays the message Hello, world.
    on-screen. This is an example of using printf()with only one argument, the for-
    mat string. In this case, the format string contains only a literal string to be dis-
    played on-screen.

  • The statement printf(“%d”, i);displays the value of the integer variable ion-
    screen. The format string contains only the format specifier %d, which tells
    printf()to display a single decimal integer. The second argument iis the name
    of the variable whose value is to be displayed.

  • The statement printf(“%d plus %d equals %d.”, a, b, a+b);displays 2
    plus 3 equals 5on-screen (assuming that aandbare integer variables with the
    values of 2 and 3 , respectively). This use of printf()has four arguments: a format
    string that contains literal text as well as format specifiers, and two variables and
    an expression whose values are to be displayed.
    Now look at the printf()format string in more detail. It can contain the following:

  • Zero, one, or more conversion commands that tell printf()how to display a value
    in its argument list. A conversion command consists of %followed by one or more
    characters.

  • Characters that are not part of a conversion command and are displayed as-is.
    The third example’s format string is %d plus %d equals %d. In this case, the three %ds
    are conversion commands, and the remainder of the string, including the spaces, is literal
    characters that are displayed directly.
    Now you can dissect the conversion command. The components of the command are
    given here and explained next. Components in brackets are optional.
    %[flag][field_width][.[precision]][l]conversion_char
    Theconversion_charis the only required part of a conversion command (other than the
    %). Table 14.5 lists the conversion characters and their meanings.


362 Day 14

22 448201x-CH14 8/13/02 11:12 AM Page 362

Free download pdf