Hatena::Groupcprogramming

C Study Diary

2008-12-17

c4ex7_ungets.cpp

17:20

Write a routine ungets(s) that will push back an entire string onto the input.


#include <stdio.h>
#include <string.h>

#define BUFSIZE 100

int buf[BUFSIZE];
int bufp = 0;

/* Getch: get a ( possibly pushed back) character. */
int getch(void)
{
   return (bufp > 0) ? buf[--bufp]: getchar();
}

/* unGetch: push character back on input. */
void ungetch(int c)
{
   if(bufp >= BUFSIZE)
      printf("\nUnGetch: too many characters\n");
   else
      buf[bufp++] = c;
}

void ungets(char s[])
{
	int c, i=0;
	for(i=strlen(s);i>=0;i--){
	
		ungetch(s[i]);
	
	}
}

int main()
{
	int c, i=0;
	char s[] = "hello this a test";
	
	printf("%s\n",s);	
	
	ungets(s);
	
	while((c=getch())!='\n'){
		printf("%c",c);
	}
	
}

Run:

$ ./c4ex7_ungets.exe
hello this a test
hello this a test