-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exercise5-2.c
84 lines (63 loc) · 1.58 KB
/
Exercise5-2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*Exercise 5-2. Write getfloat, the floating-point analog of getint.
What type does getfloat return as its function value ?*/
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
double array[SIZE];
int main()
{
int n, getint(double *);
for (n = 0; n < SIZE && getint(&array[n]) != EOF; n++)
;
for (int i=0;i<SIZE;i++)
printf("%g ",array[i]);
return (EXIT_SUCCESS);
}
#include <ctype.h>
int getch(void);
void ungetch(int);
/* getint: get next integer from input into *pn */
int getint(double *pn)
{
int c, sign,decimal=1;
while (isspace(c = getch())) /* skip white space */
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-')
{
ungetch(c); /* it is not a number */
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
c = getch();
if (!isdigit(c))
ungetch((sign==1) ? '+':'-');
for (*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + (c - '0');
if (c=='.')
c=getch();
for (; isdigit(c); c = getch())
{
*pn = 10 * *pn + (c - '0');
decimal*=10;
}
*pn *= sign;
*pn=*pn/decimal;
if (c != EOF)
ungetch(c);
return c;
}
#define BUFSIZE 100
int buf[BUFSIZE];/* buffer for ungetch */
int bufp = 0;/* next free position in buf */
int getch(void) /* get a (possibly pushed-back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back on input */
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}