Page 97
Write getfloat
, the floating-point analog of getint
. What type does getfloat
return as its function value?
#include <stdio.h>
#include <ctype.h>
#define SIZE 100
int main()
{
int i, isfloat, getfloat(float *);
float array[SIZE];
for (i = 0; i < SIZE && (isfloat = getfloat(&array[i])) != EOF;
isfloat ? i++ : (void)0)
;
for (int j = 0; j < i; j++) {
printf("%g\n", array[j]);
}
}
int getch(void);
void ungetch(int);
int getfloat(float *pf)
{
int c, sign, power;
while (isspace(c = getch()))
;
if (!isdigit(c) && c != '+' && c != '-' && c != '.' && c != EOF) {
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-') {
c = getch();
if ((c <= '0' || c >= '9') && c != '.') {
return 0;
}
}
power = 0;
for (*pf = 0; isdigit(c) || c == '.'; c = getch()) {
power *= 10;
if (c == '.') {
power = 1;
} else {
*pf = 10 * *pf + (c - '0');
}
}
if (power > 0) {
*pf /= power;
}
*pf *= sign;
if (c != EOF) {
ungetch(c);
}
return c;
}
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp >= BUFSIZE) {
printf("ungetch: too many characters\n");
} else {
buf[bufp++] = c;
}
}