将复杂声明转化为自然语言描述的程序
本程序主要借助两个相互调用的函数dlc()和dir()来读取一个复杂声明中的定义情况(例如:char (*(*x[3])())[5]
,对该声明应该是x:array[3] of point to function returning pointer to array[5] of char )。
在使用递归时,应将递归程序最里层要实现的目的为基础将函数写出来(因为递归程序必然每层的功能都一样),再考虑进入递归的条件,放入函数的适当位置。
在编写本程序时遇到枚举函数无法通过编译的情况*(/*enum { NAME, PARENS, BRACKETS } ;)
,如果有看官知晓原因的麻烦指出错误之处,感激不尽!
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define MAXTOKEN 100
#define NAME 0
#define PARENS 1
#define BRACKETS 2
/*enum { NAME, PARENS, BRACKETS } ;为什么这段声明过不了编译(error C2143: 语法错误 : 缺少“;”(在“}”的前面))*/
void dcl(void);
void dirdcl(void);
int gettoken(void);
int tokentype;
char token[MAXTOKEN];
char name[MAXTOKEN];
char datatype[MAXTOKEN];
char out[1000];
int main(void)
{
while(gettoken() != EOF){
strcpy(datatype,token);
out[0] = '\0';/*每一行都应该将out清空*/
dcl();
if(tokentype != '\n')
printf("synatax error\n");
printf("%s:%s %s",name,out,datatype);
}
return 0;
}
int gettoken(void)
{
int getch(void);
void ungetch(int);
int c;
char *p = token;
while((c = getch()) == ' ' || c == '\t')
;
if(c == '('){
if((c = getch()) == ')'){
strcpy(token,"()");
return tokentype = PARENS; /*这里return的用法要注意*/
}else{
ungetch(c);
return tokentype = '(';
}
}else if(c == '['){
for(*p++ = c;(*p++ = getch()) != ']'; )
;
*p = '\0';
return tokentype = BRACKETS;
}else if(isalpha(c)){
for(*p++ = c;isalnum(c = getch()); )
*p++ = c;
*p = '\0';
ungetch(c);//当不是字母数字之后记得把提前取的字符压回缓冲区
return tokentype = NAME;
}else
return tokentype = c;/*这里的c有可能是'\n'、'EOF'、')'和非法字符*/
}
#define BUFFSIZE 1000
int buffer[BUFFSIZE];
int buffp = 0;
int getch(void)
{
return (buffp > 0) ? buffer[--buffp] : getchar();
}
void ungetch(int c)
{
if (buffp >= BUFFSIZE)
printf("ungetch:too many characters\n");
else
buffer[buffp++] = c;
}
void dcl(void)
{
int n;
for(n = 0;gettoken() == '*'; )
n++;
dirdcl();
while(n-- > 0)
strcat(out," pointer to");/*由里层逐渐向外层添加*/
}
void dirdcl(void)
{
int type;
if(tokentype == '('){ /*又是另一个dcl*/
dcl();
if(tokentype != ')')
printf("error:missing )\n");
}else if(tokentype == NAME)
strcpy(name,token);
else
printf("error:expected name or dcl\n");
while((type = gettoken()) == BRACKETS || type == PARENS)
{
if(type == PARENS)
strcat(out," function returning");
else{
strcat(out," array");
strcat(out,token);
strcat(out," of");
}
}
}`