Sams Teach Yourself C in 21 Days

(singke) #1
data. Lines 17 through 21 have you enter and print long integers and a double. Line 23
calls the fflush()function to clear any unwanted characters from the standard input
stream. Lines 27 and 28 get the next value, a five-character integer. Because there are
width specifiers, the five-digit integer is split into two integers—one that is two charac-
ters, and one that is three characters. Line 34 calls fflush()to clear the keyboard again.
The final example, in lines 36 through 44, uses the exclude character. Line 40 uses “%[^
]”, which tells scanf()to get a string but to stop at any spaces. This effectively splits
the input.
Take the time to modify this listing and enter additional values to see what the results
are.
Thescanf()function can be used for most of your input needs, particularly those
involving numbers (strings can be input more easily with gets()). It is often worthwhile,
however, to write your own specialized input functions. You can see some examples of
user-defined functions on Day 18, “Getting More from Functions.”

358 Day 14

DOuse the gets()andscanf()functions
instead of the fgets()andfscanf()
functions if you’re using the standard
input file (stdin)only.

DON’Tforget to check the input stream
for extra characters.

DO DON’T


Controlling Output to the Screen ........................................................................


Screen output functions are divided into three general categories along the same lines as
the input functions: character output, line output, and formatted output. You were intro-
duced to some of these functions in earlier lessons. This section covers them in detail.

Character Output with putchar(),putc(), and fputc()..............................

The C library’s character output functions send a single character to a stream. The func-
tionputchar()sends its output to stdout(normally the screen). The functions fputc()
andputc()send their output to a stream specified in the argument list.

Using the putchar()Function
The prototype for putchar, which is located in stdio.h, is as follows:
int putchar(int c);

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

Free download pdf