i'm searching for a long time on net. but no use. please help me.
/* getch and ungetch to handle EOF Character In all the ungetch and getch
* functions written so far, the buf is declared as char buf[BUFSIZ].
* Changing this to int buf[BUFSIZ] enable it to handle EOF. As EOF is an
* integer declared in stdio.h having the value -1 */
#include<stdio.h>
#define BUFSIZE 100
int getch(void);
void ungetch(int c);
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
int main(void)
{
int c;
c = '*';
ungetch(c);
while((c=getch())!=EOF)
putchar(c);
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;
}
i wanted to use pointer to achieve same effect. But i failed( wrong codes are as follows). Bufp = buf
has a error.The error was that Bufp: different level between the indirection of int and char*. In my limited experience with pointer, the type of pointer Bufp is char* ,it points to char data type.char buf[BUFSIZE];
means buf[] is a array of characters. If what i said was right, why did the problem appear? was there something i ignored?
char buf[30];
char *Bufp;
Bufp = buf;
int getch(void)
{
return (Bufp >= buf) ? *(--Bufp) : getchar();
}
void ungetch(int c)
{
if (c != EOF)
*Bufp++ = c;
else
printf("no space\n");
}