K & R C Programs Exercise 5-18.

K and R C, Solution to Exercise 5-18:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to convert the C declaration into a word description and Make dcl recover from input errors.Read more about C Programming Language .
/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<string.h>
#include<ctype.h>
enum { NAME, PARENS, BRACKETS};
enum { NO, YES};
void dcl(void);
void dirdcl(void);
void errmsg(char *);


int gettoken(void);
extern int tokentype;
extern char token[];
extern char name[];
extern char out[];
extern int prevtoken;

main()
{
int type;
char temp[MAXTOKEN];
while (gettoken() !=EOF) {
strcy(out, token);
while ((type = gettoken()) != 'n')
if(type == PARENS || type == BRACKETS)
strcat(out, token);
else if(type == '*') {
sprintf(temp, "(*%s)", out);
strcpy(out, temp);
}else if(type == NAME){
sprintf(temp, "%s%s",token, out);
strcpy(out, temp);
}else
printf("Invalid input at %sn",token);
printf("%sn",out);
}
return 0;
}


//dcl:parse a declarator
void dcl(void)
{
int ns;
for(ns = 0; gettoken() == '*';)
ns++;
dirdcl();
while(ns --> 0)
strcat(out, "pointer to");
}


//dirdcl: parse a direct declaration
void dirdcl(void)
{
int type;
if(tokentype == '('){
dcl();
if(tokentype != ')')
errmsg("error:missimg)n");
}
else if(tokentype == NAME)
strcpy(name,token);
else
errmsg("error:expected name or (dcl)n");
while((type = gettoken()) == PARENS || type == BRACKETS)
if(type == PARENS)
strcat(out, "function returning");
else {
strcat(out, "array");
strcat(out, token);
strcat(out, "of");
}
}

//errmsg: prints the error message
void errmsg(char *msg)
{
printf("%sn",msg);
prevtoken = YES;
}


//get token:return next token
int gettoken(void)
{
int c, getch(void);
void ungetch(int);
char *p = token;
if(prevtoken == YES) {
prevtoken = NO;
return tokentype;
}
while((c = getch()) == ' ' || c == 't')
;
if(c == '('){
if ((c = getch()) == ')'){
strcpy(token,"()");
return tokentype = PARENS;
}
else{
ungetch(c);
return tokentype = '(';
}
}
else if(c == '['){
for(*p++ = c; (*p++ = getch()) != ']';)
;
*p = '