K & R C Programs Exercise 5-19.

K and R C, Solution to Exercise 5-19:
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 modify(K & R C Programs Exercise 5-18.) undcl so that it does not add redundant parentheses to declarations. 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>

#define MAXTOKEN 100

enum { NAME, PARENS, BRACKETS};
enum { YES, NO};



int gettoken(void);
int nexttoken(void);
extern int tokentype;
extern char token[MAXTOKEN];
char out[1000];
extern int prevtoken = NO;
//UNDCL:convert word description to declaration
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 == '*') {
if((type = nexttoken()) == PARENS || type == BRACKETS)
sprintf(temp, "(*%s)", out);
else
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;
}


//nexttoken: get the next token and push it back
int nexttoken(void)
{
int type;
extern int prevtoken;
type = gettoken();
prevtoken = YES;
return type;
}


//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 = '