aboutsummaryrefslogtreecommitdiff
path: root/5.2.c
diff options
context:
space:
mode:
Diffstat (limited to '5.2.c')
-rw-r--r--5.2.c99
1 files changed, 48 insertions, 51 deletions
diff --git a/5.2.c b/5.2.c
index e313454..b0213f1 100644
--- a/5.2.c
+++ b/5.2.c
@@ -1,78 +1,75 @@
#include <stdio.h>
#include <ctype.h>
-int getfloat(double *np);
-char getch(void);
-void ungetch(char input);
+#define MAXBUFF 100
-int
-main(void)
-{
- double num;
+int getfloat(float *pn);
+int getch(void);
+void ungetch(int input);
- getfloat(&num);
+int main(void)
+{
+ float input;
- printf("%.8g\n", num);
+ getfloat(&input);
+ printf("input: %f\n", input);
- return 0;
+ return 0;
}
-int
-getfloat(double *np)
+int getfloat(float *pn)
{
- int input, sign, divider;
+ char input, sign;
+ int decimal_divider;
- /* skip space */
- while (isspace(input = getch()))
- ;
+ while (isspace(input = getch()))
+ ;
- if (!isdigit(input) && input != EOF && input != '+' && input != '-' && input != '.') {
- ungetch(input);
- return 0;
- }
+ if (!isdigit(input) && input != '.' && input != EOF && input != '+' && input != '-') {
+ ungetch(input);
+ return 0;
+ }
- sign = (input == '-') ? -1 : 1;
+ sign = (input == '-') ? -1 : 1;
- if (input == '+' || input == '-')
- while (isspace(input = getch()))
- ;
+ if (input == '-' || input == '+') {
+ input = getch();
- for (*np = 0; isdigit(input); input = getch())
- *np = *np * 10 + input - '0';
+ if (!isdigit(input) && input != '.') {
+ ungetch((sign == -1) ? '-' : '+');
+ return 0;
+ }
+ }
- if (input == '.')
- for (divider = 1; isdigit(input = getch()); divider *= 10)
- *np = *np * 10 + input - '0';
+ for (*pn = 0; isdigit(input); input = getch())
+ *pn = (*pn * 10) + (input - '0');
- *np = *np * sign / divider;
+ if (input == '.' && !isdigit(input = getchar()))
+ ungetch('.');
- if (input != EOF)
- ungetch(input);
+ for (decimal_divider = 1; isdigit(input); input=getch(), decimal_divider *= 10)
+ *pn = (*pn * 10) + (input - '0');
- /* return last input, EOF */
- return input;
-}
+ *pn /= (float)decimal_divider * sign;
-static char buff = -1;
+ if (input != EOF)
+ ungetch(input);
-char
-getch(void)
-{
- char temp;
+ return input;
+}
- if (buff == -1)
- return getchar();
+char buff[MAXBUFF];
+int bpos = 0;
- temp = buff;
- buff = -1;
- return temp;
+int getch(void)
+{
+ return (bpos) ? buff[--bpos] : getchar();
}
-void
-ungetch(char input)
+void ungetch(int input)
{
- if (buff == -1)
- buff = input;
- else
- printf("Err: buffer is full\n");
+ if (bpos < MAXBUFF)
+ buff[bpos++] = input;
+ else
+ printf("err: buff full\n");
}