Sams Teach Yourself C in 21 Days

(singke) #1
Working with the Screen, Printer, and Keyboard 343

14


10: putchar(ch);
11:
12: return 0;
13: }

This is what’s typed in.
This is what’s typed in.
On line 9, the getchar()function is called and waits to receive a character from
stdin. Because getchar()is a buffered input function, no characters are
received until you press Enter. However, each key you press is echoed immediately on
the screen.
When you press Enter, all the characters you entered, including the newline, are sent to
stdinby the operating system. The getchar()function returns the characters one at a
time, assigning each in turn to ch.
Each character is compared to the newline character ‘\n’and, if not equal, displayed on-
screen with putchar(). When a newline is returned by getchar(), thewhileloop termi-
nates.
Thegetchar()function can be used to input entire lines of text, as shown in Listing
14.3. However, other input functions are better suited for this task, as you’ll learn later
today.

LISTING14.3 getchar2.c. Using the getchar()function to input an entire line of text
1: /* Using getchar() to input strings. */
2:
3: #include <stdio.h>
4:
5: #define MAX 80
6:
7: int main( void )
8: {
9: char ch, buffer[MAX+1];
10: int x = 0;
11:
12: while ((ch = getchar()) != ‘\n’ && x < MAX)
13: buffer[x++] = ch;
14:
15: buffer[x] = ‘\0’;
16:
17: printf(“%s\n”, buffer);
18:
19: return 0;
20: }

LISTING14.2 continued

INPUT/
OUTPUT

ANALYSIS

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

Free download pdf