PL0语言词法分析程序(C++版)

    技术2022-05-11  148

    #include<fstream.h>#include<string.h>#include<ctype.h>#include<math.h>#include<stdlib.h>char* word[]=   {"begin","call","const","do","end","if","odd",                 "procedure","read","then","var","while","write"};char* wsym[]=   {"beginsym","callsym","constsym","dosym","endsym",                 "ifsym","oddsym","procsym","readsym","thensym",        "varsym","whilesym","writesym"};char* symbol[]= {"+","-","*","/","(",")","=",",",".","#",";"};char* sysm[]=   {"plus","minus","times","slash","lparen","rparen",                 "eql","comma","peroid","neg","semicolon"};void main(){ char*sym=new char[20]; int num=0; char ch; char buffer[100]; int index=0; ifstream in("test1.java"); ofstream out("result.txt"); while(!in.eof()) {  ch=in.get();  while(ch==' ') ch=in.get();        if(isalpha(ch)){           //如果为字母打头,则为保留字或标识符  while(isalpha(ch)||isdigit(ch)){   buffer[index++]=ch;   ch=in.get();  }  buffer[index]='/0';  index=0;  int i=0;  for(i=0; i<13; i++){   if(!strcmp(buffer,word[i])) break;  }  if(i==13) {sym="ident"; out<<"( "<<sym<<" , "<<buffer<<" )"<<endl;}  else if(i<13) {   sym=wsym[i]; out<<"( "<<sym<<" , "<<buffer<<" )"<<endl;  }  }

      else if(isdigit(ch)){           //如果是数字打头,则拼数   char a[20];   sym="number";   int i=0;      a[i]=ch;      while(isdigit(ch)){      ch=in.get();      a[++i]=ch;   }      a[i]='/0';      i=0;   num=atol(a);            out<<"( "<<sym<<" , "<<num<<" )"<<endl;  }

      if(ch==':'){   ch=in.get();   while(ch==' ') ch=in.get();   if(ch=='=') {     sym="becomes";                out<<"( "<<sym<<" , "<<":="<<" )"<<endl;   }   else{    sym="nul";                out<<"( "<<sym<<" , "<<":"<<" )"<<endl;   }  } 

          else  if(ch=='<'){  ch=in.get();  while(ch==' ' && !isdigit(ch) && !isalpha(ch)) ch=in.get();  if(ch=='='){   sym="leq";            out<<"( "<<sym<<" , "<<"<="<<" )"<<endl;  }  else{   sym="lss";   out<<"( "<<sym<<" , "<<"<"<<" )"<<endl;  } }

         else  if(ch=='>'){  ch=in.get();  while(ch==' ' && !isdigit(ch) && !isalpha(ch)) ch=in.get();  if(ch=='='){   sym="geq";            out<<"( "<<sym<<" , "<<">="<<" )"<<endl;  }  else{   sym="gtr";   out<<"( "<<sym<<" , "<<">"<<" )"<<endl;  } }

      else{   int count=0;   buffer[0]=ch;   buffer[1]='/0';   int i=0;   for(i=0; i<11; i++)    if(!strcmp(buffer,symbol[i])) break;    if(i<11){     sym=sysm[i];                 out<<"( "<<sym<<" , "<<ch<<" )"<<endl;    }  } } in.close();} 


    最新回复(0)