From ba3e350d9794cbd39c57a2ad74ea346e8a197401 Mon Sep 17 00:00:00 2001 From: sinanmohd Date: Thu, 16 Jun 2022 18:11:56 +0530 Subject: start 5 --- 5.2.c | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 5.2.c (limited to '5.2.c') diff --git a/5.2.c b/5.2.c new file mode 100644 index 0000000..e313454 --- /dev/null +++ b/5.2.c @@ -0,0 +1,78 @@ +#include +#include + +int getfloat(double *np); +char getch(void); +void ungetch(char input); + +int +main(void) +{ + double num; + + getfloat(&num); + + printf("%.8g\n", num); + + return 0; +} + +int +getfloat(double *np) +{ + int input, sign, divider; + + /* skip space */ + while (isspace(input = getch())) + ; + + if (!isdigit(input) && input != EOF && input != '+' && input != '-' && input != '.') { + ungetch(input); + return 0; + } + + sign = (input == '-') ? -1 : 1; + + if (input == '+' || input == '-') + while (isspace(input = getch())) + ; + + for (*np = 0; isdigit(input); input = getch()) + *np = *np * 10 + input - '0'; + + if (input == '.') + for (divider = 1; isdigit(input = getch()); divider *= 10) + *np = *np * 10 + input - '0'; + + *np = *np * sign / divider; + + if (input != EOF) + ungetch(input); + + /* return last input, EOF */ + return input; +} + +static char buff = -1; + +char +getch(void) +{ + char temp; + + if (buff == -1) + return getchar(); + + temp = buff; + buff = -1; + return temp; +} + +void +ungetch(char input) +{ + if (buff == -1) + buff = input; + else + printf("Err: buffer is full\n"); +} -- cgit v1.2.3