Last active
August 17, 2019 22:25
-
-
Save cynx/d9e949d86ef0445c83e8 to your computer and use it in GitHub Desktop.
C program to illustrate use of getch() and ungetch()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define BUFSIZE 100 | |
int getch(void); | |
void ungetch(int c); | |
int buf[BUFSIZE]; /* buffer for ungetch */ | |
int bufp = 0; /* next free position in buf */ | |
int main(void) | |
{ | |
int i = 0; | |
char ch; | |
puts("Input an integer followed by a char:"); | |
/* read chars until non digit or EOF */ | |
while ((ch = getch()) != EOF && isdigit(ch)) | |
i = 10 * i + ch - 48; /* convert ASCII into int value */ | |
/* if non digit char was read, push it back into input buffer */ | |
if (ch != EOF) | |
ungetch(ch); | |
printf("\n\ni = %d, next char in buffer = %c\n", i, getch()); | |
return 0; | |
} | |
/* getch: get a (possibly pushed back) character */ | |
int getch(void) | |
{ | |
return (bufp > 0) ? buf[--bufp] : getchar(); | |
} | |
/* ungetch: push a character back onto the input */ | |
void ungetch(int c) | |
{ | |
if (bufp >= BUFSIZE) | |
printf("ungetch: too many characters \n"); | |
else | |
buf[bufp++] = c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment