Sams Teach Yourself C in 21 Days

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

14


LISTING14.6 fgets.c. Using thefgets()function for keyboard input
1: /* Demonstrates the fgets() function. */
2:
3: #include <stdio.h>
4:
5: #define MAXLEN 10
6:
7: int main( void )
8: {
9: char buffer[MAXLEN];
10:
11: puts(“Enter text a line at a time; enter a blank to exit.”);
12:
13: while (1)
14: {
15: fgets(buffer, MAXLEN, stdin);
16:
17: if (buffer[0] == ‘\n’)
18: break;
19:
20: puts(buffer);
21: }
22: return 0;
23: }

Enter text a line at a time; enter a blank to exit.
Roses are red
Roses are
red
Violets are blue
Violets a
re blue
Programming in C
Programmi
ng in C

Is for people like you!
Is for pe
ople like
you!
Line 15 contains the fgets()function. When running the program, enter lines of length
less than and greater than MAXLENto see what happens. If a line greater than MAXLENis
entered, the first MAXLEN - 1characters are read by the first call to fgets(); the remain-
ing characters remain in the keyboard buffer and are read by the next call to fgets()or
any other function that reads from stdin. The program exits when a blank line is entered
(lines 17 and 18).

INPUT/
OUTPUT

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

Free download pdf