aboutsummaryrefslogtreecommitdiff
path: root/5.1.c
diff options
context:
space:
mode:
authorsinanmohd <pcmsinan@gmail.com>2022-06-16 18:11:56 +0530
committersinanmohd <pcmsinan@gmail.com>2022-06-16 18:11:56 +0530
commitba3e350d9794cbd39c57a2ad74ea346e8a197401 (patch)
tree63234a34ca60f944fc1bc3469211b122969d0267 /5.1.c
parent9aece3aa53b56d096513ebfc48fba2cca625a299 (diff)
start 5
Diffstat (limited to '5.1.c')
-rw-r--r--5.1.c74
1 files changed, 74 insertions, 0 deletions
diff --git a/5.1.c b/5.1.c
new file mode 100644
index 0000000..a0e0559
--- /dev/null
+++ b/5.1.c
@@ -0,0 +1,74 @@
+#include <stdio.h>
+#include <ctype.h>
+
+int getint(int *np);
+char getch(void);
+void ungetch(char input);
+
+int
+main(void)
+{
+ int num;
+
+ getint(&num);
+
+ printf("%d\n", num);
+
+ return 0;
+}
+
+int
+getint(int *np)
+{
+ int input, sign;
+
+ /* skip space */
+ while (isspace(input = getch()))
+ ;
+
+ if (!isdigit(input) && input != EOF && 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';
+
+ *np *= sign;
+
+ if (input != EOF)
+ ungetch(input);
+
+ /* return last digit or 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");
+}