Three_Code.cpp
上传用户:wangchao
上传日期:2013-05-12
资源大小:9k
文件大小:2k
- #include<stdio.h>
- #include <iostream.h>
- #include <string.h>
- #include <ctype.h>
- #define CODESIZE 100
- int i=1,j=0;
- char token;
- char id[20];
- typedef enum{plus,Assign} optype;
- typedef enum{opkind,constkind,idkind }nodekind;
- typedef struct streenode
- {
- nodekind kind;
- optype op;
- struct streenode *lchild,*rchild;
- int val;
- char * strval;
- }streenode;
- typedef streenode* syntaxtree;
- void gencode(syntaxtree t)
- {
- char codestr[CODESIZE];
- if(t!=NULL)
- {
- switch(t->kind)
- {
- case opkind:
- switch(t->op)
- {
- case plus:
- gencode(t->lchild);
- gencode(t->rchild);
- t->strval=new char[10];
- sprintf(t->strval,"t%d",i++);
- sprintf(codestr,"%s=%s+%s",t->strval,t->lchild->strval,t->rchild->strval);
- cout<<codestr<<endl;
- break;
- case Assign:
- gencode(t->lchild);
- sprintf(codestr,"%s=%s",t->strval,t->lchild->strval);
- sprintf(t->strval,t->lchild->strval);
- cout<<codestr<<endl;
- break;
- }
- break;
- case constkind:
- break;
- case idkind:
- break;
- }
- }
- }
- syntaxtree exp();
- void getid()
- {
- token=getchar();
- while(isalnum(token))
- {
- id[j++]=token;
- token=getchar();
- }
- id[j]='';
- j=0;
- }
- syntaxtree factor()
- {
- syntaxtree temp;
- if(token=='(')
- {
- temp=exp();
- if(token!=')')
- {
- cout<<"error";
- }
- else getid();
- }
- else
- {
- temp=new streenode;
- temp->kind=idkind;
- temp->strval=new char[10];
- sprintf(temp->strval,id);
- temp->lchild=temp->rchild=NULL;
- }
- return temp;
- }
- syntaxtree aexp()
- {
- syntaxtree temp;
- temp=factor();
- while(token=='+')
- {
- syntaxtree temp1;
- temp1=new streenode;
- temp1->kind=opkind;
- temp1->op=plus;
- temp1->lchild=temp;
- getid();
- temp1->rchild=factor();
- temp=temp1;
- }
- return temp;
- }
- syntaxtree exp()
- {
- getid();
- if(strlen(id)!=0&&token=='=')
- {
- syntaxtree temp;
- temp=new streenode;
- temp->strval=new char[20];
- sprintf(temp->strval,id);
- temp->kind=opkind;
- temp->op=Assign;
- temp->rchild=NULL;
- temp->lchild=exp();
- return temp;
- }
- if(token!='=')
- {
- syntaxtree temp1;
- temp1=aexp();
- return temp1;
- }
- }
- int main(int argc, char* argv[])
- {
- syntaxtree t;
- cout<<"请输入一个表达式:"<<endl;
- t=exp();
- cout<<"三地址代码如下:"<<endl;
- gencode(t);
- getchar();
- return 0;
- }