Sams Teach Yourself C in 21 Days

(singke) #1
12: x = get_int();
13:
14: printf(“You entered %d.\n”, x);
15: }
16:
17: int get_int(void)
18: {
19: int ch, i, sign = 1;
20:
21: /* Skip over any leading white space. */
22:
23: while ( isspace(ch = getchar()) )
24: ;
25:
26: /* If the first character is nonnumeric, unget */
27: /* the character and return 0. */
28:
29: if (ch != ‘-’ && ch != ‘+’ && !isdigit(ch) && ch != EOF)
30: {
31: ungetc(ch, stdin);
32: return 0;
33: }
34:
35: /* If the first character is a minus sign, set */
36: /* sign accordingly. */
37:
38: if (ch == ‘-’)
39: sign = -1;
40:
41: /* If the first character was a plus or minus sign, */
42: /* get the next character. */
43:
44: if (ch == ‘+’ || ch == ‘-’)
45: ch = getchar();
46:
47: /* Read characters until a nondigit is input. Assign */
48: /* values, multiplied by proper power of 10, to i. */
49:
50: for (i = 0; isdigit(ch); ch = getchar() )
51: i = 10 * i + (ch - ‘0’);
52:
53: /* Make result negative if sign is negative. */
54:
55: i *= sign;
56:
57: /* If EOF was not encountered, a nondigit character */
58: /* must have been read in, so unget it. */
59:

508 Day 17

LISTING17.16 continued

28 448201x-CH17 8/13/02 11:13 AM Page 508

Free download pdf