summaryrefslogtreecommitdiffstats
path: root/5/2.c
diff options
context:
space:
mode:
authorSadeep Madurange <smadurange@users.noreply.github.com>2021-12-27 19:01:19 +0800
committerSadeep Madurange <smadurange@users.noreply.github.com>2021-12-27 19:01:19 +0800
commitfb67d9ce5a71feee7b091d56a046c2ae42baaefe (patch)
tree6a9f360d74226e3808e7e6255c7c993dc03dbbf1 /5/2.c
parent66d4288e9c9bc92e7b13587b4da575d84416c4d3 (diff)
downloadk&r-exercises-fb67d9ce5a71feee7b091d56a046c2ae42baaefe.tar.gz
5.2
Diffstat (limited to '5/2.c')
-rw-r--r--5/2.c73
1 files changed, 73 insertions, 0 deletions
diff --git a/5/2.c b/5/2.c
new file mode 100644
index 0000000..db37319
--- /dev/null
+++ b/5/2.c
@@ -0,0 +1,73 @@
+#include <ctype.h>
+#include <stdio.h>
+
+#define BUFSIZE 100
+
+int getfloat(float *);
+
+int main(int argc, char *argv[]) {
+ int rc;
+ float f;
+
+ while ((rc = getfloat(&f)) != EOF && rc != 0)
+ printf("\t%.8g\n", f);
+
+ if (rc == 0)
+ printf("error: not a valid number\n");
+
+ return 0;
+}
+
+char buf[BUFSIZE];
+int bufp = 0;
+
+int getch() { return (bufp > 0) ? buf[--bufp] : getchar(); }
+
+void ungetch(int c) {
+ if (bufp >= BUFSIZE)
+ printf("ungetch: too many characters\n");
+ else
+ buf[bufp++] = c;
+}
+
+int getfloat(float *pf) {
+ int c, sign, rad, div;
+
+ rad = 0;
+
+ while (isspace(c = getch()))
+ ;
+
+ if (!isdigit(c) && c != EOF && c != '+' && c != '-' && c != '.') {
+ ungetch(c);
+ return 0;
+ }
+
+ sign = (c == '-') ? -1 : 1;
+
+ if ((c == '+' || c == '-') && !isdigit(c = getch()) && c != '.') {
+ ungetch(c);
+ return 0;
+ }
+
+ for (*pf = 0.0, div = 1.0; isdigit(c) || c == '.'; c = getch()) {
+ if (c == '.') {
+ if (rad > 0)
+ return 0;
+ rad++;
+ continue;
+ }
+
+ if (rad)
+ div *= 10;
+
+ *pf = 10.0 * *pf + (c - '0');
+ }
+
+ *pf = (sign * *pf) / div;
+
+ if (c != EOF)
+ ungetch(c);
+
+ return c;
+} \ No newline at end of file