/* EXERCISE 5-2 */ /* getfloat STILL RETURNS int BUT TAKES AS ITS ARGUMENT A */ /* POINTER TO DOUBLE. */ #include <stdio.h> int getfloat(double *); void showpb(void); main() { double c; int retval; printf("getfloat RETURNED: %d\n", retval = getfloat(&c)); if (retval == 0) printf("NO NUMBER FOUND\n"); else printf("NUMBER FOUND: %g\n", c); showpb(); printf("\nEND OF PROGRAM\n"); return 0; } #include <ctype.h> int getch(void); void ungetch(int); /* GETFLOAT: GET NEXT FLOAT FROM INPUT INTO *pn */ int getfloat(double *pn) { int c, s, sign, power; int sfound = 0, dfound = 0, pfound = 0; *pn = 0; power = 1; while (isspace(c = getch())) /* SKIP WHITE SPACE */ ; if (!isdigit(c) && c != EOF && c != '+' && c != '-' && c != '.') { ungetch(c); /* IT'S NOT A NUMBER */ return(0); } sign = (c == '-') ? -1 : 1; if (c == '+' || c == '-') { sfound = 1; s = c; c = getch(); } if (isdigit(c)) for (dfound = 1; isdigit(c); c = getch()) *pn = 10 * *pn + (c - '0'); if (c == '.') { pfound = 1; c = getch(); } if (isdigit(c)) for (dfound = 1; isdigit(c); c = getch()) { *pn = 10 * *pn + (c - '0'); power *= 10; } if (!dfound) { /* IT'S NOT A NUMBER */ if (c != EOF) ungetch(c); if (pfound) ungetch('.'); if (sfound) ungetch(s); return(0); } *pn *= sign; *pn /= power; if (c != EOF) ungetch(c); return(c); } #define BUFSIZE 100 char buf[BUFSIZE]; /* BUFFER FOR ungetch */ int bufp = 0; /* NEXT FREE POSITION IN buf */ /* GETCH: GET A (POSSIBLY PUSHED BACK) CHARACTER */ int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } /* UNGETCH: PUSH CHARACTER BACK ON INPUT */ int ungetch(int c) { if (bufp >= BUFSIZE) printf("UNGETCH: TOO MANY CHARACTERS\n"); else buf[bufp++] = c; } /* SHOWPB: PRINT THE PUSHED-BACK CHARACTERS */ void showpb(void) { int c; while (bufp > 0) if ((c = buf[--bufp]) == '\n') printf("PUSHBACK OF: \\n\n"); else printf("PUSHBACK OF: %c\n", c); }