Hatena::Groupcprogramming

C Study Diary

2008-12-17

c4ex8_ungetch.cpp

17:23

Suppose that there will never be more than one character of pushback. Modify getch and ungetch accordingly.

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

int save=NULL;

/* Getch: get a ( possibly pushed back) character. */
int getch(void)
{
	int t;
	if(save!=NULL){
		t=save;
		save=NULL;
		return t;
	} 
	else return getchar();
   
}  

/* unGetch: push character back on input. */
void ungetch(int c)
{  
	if(save != NULL)
		printf("ungetch: too many characters\n");
	else  
		save = 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 = "h";
	char t;
	
	printf("%s\n",s);		
	ungets(s);	
	printf("%c\n",getch());	
	
	s = "hello";	
	printf("%s\n",s);		
	ungets(s);	
	printf("%c\n",getch());
	
	t = 'A';	
	printf("%c\n",t);		
	ungetch(t);	
	printf("%c\n",getch());
}

Run:

$ ./c4ex8_ungetch.exe
h
h
hello
ungetch: too many characters
ungetch: too many characters
ungetch: too many characters
ungetch: too many characters
o
A
A