From 49af8a805ef65f42cb4367eb47bf2d04e928454b Mon Sep 17 00:00:00 2001 From: kdeng00 Date: Sat, 27 Feb 2021 23:49:24 -0500 Subject: [PATCH] Finished exercise 5.2 --- ch_05/exercise_05-02/main.c | 106 +++++++++++++++++++++++++++ ch_05/exercise_05-02/main_template.c | 15 ---- 2 files changed, 106 insertions(+), 15 deletions(-) create mode 100644 ch_05/exercise_05-02/main.c delete mode 100644 ch_05/exercise_05-02/main_template.c diff --git a/ch_05/exercise_05-02/main.c b/ch_05/exercise_05-02/main.c new file mode 100644 index 0000000..a0591b0 --- /dev/null +++ b/ch_05/exercise_05-02/main.c @@ -0,0 +1,106 @@ +/* + * + * Exercise 5-2. Write getfloat, the floating-point analog of getint. What type does getfloat + * return as its function value? + * + * Author: Kun Deng + */ + +#include +#include +#include + + +#define BUFSIZE 100 +#define SIZE 1024 + +int getch(void); +void ungetch(int); + +int getfloat(float *ptr); + + +int main(void) +{ + int n; + float array[SIZE]; + + for(n=0; n= 0; n--) + { + printf("%f ",array[n]); + } + + printf("\n"); + + return 0; +} + +int getfloat(float *ptr) +{ + int c,sign; + float power; + + while(isspace(c = getch())) + ; + + if(!isdigit(c) && c != EOF && c != '+' && c != '-' && c != '.') + { + ungetch(c); + return 0; + } + + sign = (c == '-') ? -1: 1; + + if(c == '+' || c == '-') + { + c = getch(); + } + + for(*ptr = 0.0; isdigit(c); c = getch()) + { + *ptr = 10.0 * (*ptr) + (c - '0'); + } + + if(c == '.') + { + c = getch(); + } + + for(power=1.0; isdigit(c); c = getch()) + { + *ptr = 10.0 * (*ptr) + (c - '0'); /* fractional part */ + power *= 10.0; + } + + *ptr *= sign / power; + + if(c != EOF) + { + ungetch(c); + } + + return c; +} + +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; + } +} diff --git a/ch_05/exercise_05-02/main_template.c b/ch_05/exercise_05-02/main_template.c deleted file mode 100644 index 29c3190..0000000 --- a/ch_05/exercise_05-02/main_template.c +++ /dev/null @@ -1,15 +0,0 @@ -/* - * - * Exercise 5-2. Write getfloat, the floating-point analog of getint. What type does getfloat - * return as its function value? - * - * Author: Kun Deng - */ - - -int main() -{ - - - return 0; -}