Programming in C

(Barry) #1

348 Chapter 16 Input and Output Operations in C


Character I/O:getcharand putchar


Thegetcharfunction proved convenient when you wanted to read data from a single
character at a time.You saw how you could develop a function called readLineto read
an entire line of text from your terminal.This function repeatedly called getcharuntil a
newline character was read.
There is an analogous function for writing data to the terminal a single character at a
time.The name of this function is putchar.
A call to the putcharfunction is quite simple:The only argument it takes is the char-
acter to be displayed. So, the call
putchar (c);
in which cis defined as type char, has the effect of displaying the character contained
in c.
The call
putchar ('\n');
has the effect of displaying the newline character, which, as you know, causes the cursor
to move to the beginning of the next line.

Formatted I/O:printfand scanf


You have been using the printfand scanffunctions throughout this book. In this sec-
tion, you learn about all of the options that are available for formatting data with these
functions.
The first argument to both printfand scanfis a character pointer.This points to
the format string.The format string specifies how the remaining arguments to the func-
tion are to be displayed in the case of printf, and how the data that is read is to be
interpreted in the case of scanf.

The printfFunction


You have seen in various program examples how you could place certain characters
between the %character and the specific so-called conversion character to more precisely
control the formatting of the output. For example, you saw in Program 5.3A how an
integer value before the conversion character could be used to specify a field width.The
format characters %2ispecified the display of an integer value right-justified in a field
width of two columns.You also saw in exercise 6 in Chapter 5, “Program Looping,” how
a minus sign could be used to left-justify a value in a field.
The general format of a printfconversion specification is as follows:
%[flags][width][.prec][hlL]type
Optional fields are enclosed in brackets and must appear in the order shown.
Ta b les 16.1, 16.2, and 16.3 summarize all possible characters and values that can be
placed directly after the %sign and before the typespecification inside a format string.
Free download pdf