习题5-19 修改undcl程序,使它在把文字描述转化为声明的过程中不会生成多余的圆括号

来源:互联网 发布:网络hk什么意思 编辑:程序博客网 时间:2024/06/03 13:45

错误程序:

#include <stdio.h>#include <string.h>#include <ctype.h>#define MAXTOKEN 100enum {NAME,PARENS,BRACKETS};enum {NO,YES};int  gettoken(void);int  tokentype;char token[MAXTOKEN];char name[MAXTOKEN];char out[1000];int prevtoken;main(){    int type;    char temp[MAXTOKEN];    while(gettoken()!='\n'){        strcpy(out,token);        while((type=gettoken())!=EOF)            if(type==PARENS || type==BRACKETS)                strcat(out,token);            else if(type=='*'){                if((type==gettoken())==PARENS || type==BRACKETS)                    sprintf(temp,"(*%s)",out);                else if(type==NAME)                    sprintf(temp,"*%s",out);                prevtoken=YES;                strcpy(out,temp);            }            else if(type==NAME){                sprintf(temp,"%s %s",token,out);                strcpy(out,temp);            }            else                printf("invalid input at %s\n",token);        printf("%s\n",out);    }}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='\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;}#define BUFSIZE 100char buf[BUFSIZE];int bufp=0;int getch(void){    return (bufp>0)? buf[--bufp]:getchar();}void ungetch(int c){    if(bufp>=BUFSIZE)        printf("ungetch: too many characters\n");    else        buf[bufp++]=c;}

输入输出如下:

x * charchar ?﹖(\nx * charchar x char

修改:程序第27行==改成=。

0 0
原创粉丝点击