Sams Teach Yourself C in 21 Days

(singke) #1
A better solution is to make sure there are no extra characters waiting in stdinbefore
prompting the user for input. You can do this by calling gets(), which reads any remain-
ing characters from stdin, up to and including the end of the line. Rather than calling
gets()directly from the program, you can put it in a separate function with the descrip-
tive name of clear_kb(). This function is shown in Listing 14.7.

LISTING14.7 clearing.c. Clearingstdinof extra characters to avoid errors
1: /* Clearing stdin of extra characters. */
2:
3: #include <stdio.h>
4:
5: void clear_kb(void);
6:
7: int main( void )
8: {
9: int age;
10: char name[20];
11:
12: /* Prompt for user’s age. */
13:
14: puts(“Enter your age.”);
15: scanf(“%d”, &age);
16:
17: /* Clear stdin of any extra characters. */
18:
19: clear_kb();
20:
21: /* Now prompt for user’s name: */
22:
23: puts(“Enter your first name:”);
24: scanf(“%s”, name);
25: /* Display the data. */
26:
27: printf(“Your age is %d.\n”, age);
28: printf(“Your name is %s.\n”, name);
29:
30: return 0;
31: }
32:
33: void clear_kb(void)
34:
35: /* Clears stdin of any waiting characters. */
36: {
37: char junk[80];
38: gets(junk);
39: }

354 Day 14

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

Free download pdf