Sams Teach Yourself C in 21 Days

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

14


10: while ((ch = getch()) != ‘\r’)
11: putchar(ch);
12:
13: return 0;
14: }

Testing the getch() function
When this program runs,getch()returns each character as soon as you press a
key—it doesn’t wait for you to press Enter. There’s no echo, so the only reason
that each character is displayed on-screen is the call to putchar(). To get a better under-
standing of how getch()works, add a semicolon to the end of line 10 and remove line
11 (putchar(ch)). When you rerun the program, you will find that nothing you type is
echoed to the screen. The getch()function gets the characters without echoing them to
the screen. You know the characters are being gotten because the original listing used
putchar()to display them.
Why does this program compare each character to \rinstead of to \n? The code \ris the
escape sequence for the carriage return character. When you press Enter, the keyboard
device sends a carriage return to stdin. The buffered character input functions automati-
cally translate the carriage return to a newline, so the program must test for \nto deter-
mine whether Enter has been pressed. The unbuffered character input functions don’t
translate, so a carriage return is input as \r, and that’s what the program must test for.
Listing 14.5 uses getch()to input an entire line of text. Running this program clearly
illustrates that getch()doesn’t echo its input. With the exception of substituting getch()
forgetchar(), this program is virtually identical to Listing 14.3.

LISTING14.5 getch2.c. Using the getch()function to input an entire line
1: /* Using getch() to input strings. */
2: /* Non-ANSI code */
3: #include <stdio.h>
4: #include <conio.h>
5:
6: #define MAX 80
7:
8: int main( void )
9: {
10: char ch, buffer[MAX+1];
11: int x = 0;
12:
13: while ((ch = getch()) != ‘\r’ && x < MAX)

LISTING14.4 continued

OUTPUT

ANALYSIS

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

Free download pdf