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

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