Sams Teach Yourself C in 21 Days

(singke) #1
17:
18: if (message[count] == ‘\0’)
19: {
20: putchar(‘\n’);
21: break;
22: }
23: else
24:
25: /* If end of string not found, write the next character. */
26:
27: putchar(message[count]);
28: }
29: return 0;
30: }

Displayed with putchar().

Using the putc()andfputc()Functions
Theputc()andfputc()functions perform the same action—sending a single character
to a specified stream. putc()is a macro implementation of fputc(). You’ll learn about
macros on Day 21, “Advanced Compiler Use.” For now, just stick to fputc(). Its proto-
type is
int fputc(int c, FILE *fp);
TheFILE *fppart might puzzle you. You pass fputc()the output stream in this argu-
ment. (You’ll learn more about this on Day 16.) If you specify stdoutas the stream,
fputc()behaves exactly the same as putchar(). Thus, the following two statements are
equivalent:
putchar(‘x’);
fputc(‘x’, stdout);

Usingputs()andfputs()for String Output ..............................................

Your programs display strings on-screen more often than they display single characters.
The library function puts()displays strings. The function fputs()sends a string to a
specified stream; otherwise, it is identical to puts(). The prototype for puts()is
int puts(char *cp);
*cpis a pointer to the first character of the string that you want displayed. The puts()
function displays the entire string up to but not including the terminating null character,
adding a new line at the end. Then puts()returns a positive value if successful or EOFon
error. (Remember,EOFis a symbolic constant with the value -1; it is defined in stdio.h.)

360 Day 14

LISTING14.11 continued

OUTPUT

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

Free download pdf