summaryrefslogtreecommitdiffstats
path: root/5
diff options
context:
space:
mode:
authorSadeep Madurange <smadurange@users.noreply.github.com>2021-12-27 18:17:39 +0800
committerSadeep Madurange <smadurange@users.noreply.github.com>2021-12-27 18:17:39 +0800
commit17dfe130ef58ed790d46b01637b1a12afce456bd (patch)
tree362172edf0914b2afbe4ee863700525f9647fa7d /5
parent380e760eb23ea70d013726b2f3cbfa726c23aeb6 (diff)
downloadk&r-exercises-17dfe130ef58ed790d46b01637b1a12afce456bd.tar.gz
5.1
Diffstat (limited to '5')
-rw-r--r--5/1.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/5/1.c b/5/1.c
new file mode 100644
index 0000000..19e4bf2
--- /dev/null
+++ b/5/1.c
@@ -0,0 +1,53 @@
+#include <ctype.h>
+#include <stdio.h>
+
+#define BUFSIZE 100
+
+int getint(int *);
+
+int main(int argc, char *argv[]) {
+ int rc, n;
+
+ while ((rc = getint(&n)) != EOF && rc != 0)
+ printf("\t%d\n", 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 getint(int *pn) {
+ int c, sign;
+
+ while (isspace(c = getch()))
+ ;
+
+ if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
+ ungetch(c);
+ return 0;
+ }
+
+ sign = (c == '-') ? -1 : 1;
+
+ if (c == '+' || c == '-')
+ c = getch();
+
+ for (*pn = 0; isdigit(c); c = getch())
+ *pn = 10 * *pn + (c - '0');
+ *pn *= sign;
+
+ if (c != EOF)
+ ungetch(c);
+
+ return c;
+} \ No newline at end of file