Encoders
Hub for Computer Whizzes Register to join us

Encoders > More... > C > Program

/* Function getword(word,lim) to return identifiers, keywords,
   preprocessor directives, character constants, string constants
   and ignore comments. */

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

#define MAXWORD	100

int getword(char *,int);

main()
{
	int c;
	char word[MAXWORD];

	while((c=getword(word,MAXWORD))!=EOF)
		if(isalpha(c)||c=='_')
                        printf("identifier/keyword:     %s\n",word);
		else if(c=='#')
                        printf("preprocessor directive: %s\n",word);
		else if(c=='\'')
                        printf("character constant:     %s\n",word);
                else if(c=='\"')
                        printf("string constant:        %s\n",word);
		else if(c=='\0')
                        printf("comment ignored!\n");
		else
                        printf("unknown character:      %c\n",c);
}
		
int getword(char *word, int lim)
{
	int c,getch(void);
	void ungetch(int);
	char *w=word;
	
	while(isspace(c=getch()))
		;
	if(c!=EOF)
		*w++ = c;
	else
		return c;
	if(isalpha(c)||c=='_'||c=='#')
	{
                for(;--lim>0;w++)
                        if(!isalnum(*w = getch()) && *w!='_')
			{
				ungetch(*w);
				break;
			}
	}
	else if(c=='/')
	{
		if((c=getch())=='*')
			while((c=getch())!=EOF)
				if(c=='*')
					if((c=getch())=='/')
						break;
		else
			ungetch(c);
		return '\0';
	}
        else if(c=='\"' || c=='\'')
		while((*w++=getch())!=c)
			;
	*w = '\0';
	return word[0];
}
 
char buf[100];
int bufp=0;

int getch(void)
{
        return(bufp>0)?buf[--bufp]:getchar();
}

void ungetch(int c)
{
        if(bufp>=100)
                printf("error: buffer overflow\n");
	else
		buf[bufp++]=c;
}