zoukankan      html  css  js  c++  java
  • 词法分析器

    //源代码
    #include <stdio.h> #include <string.h> char string[80],simbol[8],ch; int wordID,index,m,n,sum; char *rwtab[6]={"begin","if","then","while","do","end"}; void scaner(void); main() { int index=0; printf("输入代码串(#号结束):"); do{ scanf("%c",&ch); string[index++]=ch; }while(ch!='#'); index=0; do{ scaner(); switch(wordID) { case 11: printf("( %-10d%5d )\n",sum,wordID); break; case -1: printf("错误\n"); return 0; break; default: printf("( %-10s%5d )\n",simbol,wordID); break; } }while(wordID!=0); return 0; } void scaner(void) { sum=0; for(m=0;m<8;m++) simbol[m++]= NULL; ch=string[index++]; m=0; while((ch==' ')||(ch=='\n')) ch=string[index++]; if(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A'))) { while(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A'))||((ch>='0')&&(ch<='9'))) { simbol[m++]=ch; ch=string[index++]; } index--; wordID=10; for(n=0;n<6;n++) if(strcmp(simbol,rwtab[n])==0) { wordID=n+1; break; } } else if((ch>='0')&&(ch<='9')) { while((ch>='0')&&(ch<='9')) { sum=sum*10+ch-'0'; ch=string[index++]; } index--; wordID=11; } else { switch(ch) { case '<': simbol[m++]=ch; ch=string[index++]; if(ch=='=') { wordID=22; simbol[m++]=ch; } else { wordID=20; index--; } break; case '>': simbol[m++]=ch; ch=string[index++]; if(ch=='=') { wordID=24; simbol[m++]=ch; } else { wordID=23; index--; } break; case '+': simbol[m++]=ch; ch=string[index++]; if(ch=='+') { wordID=17; simbol[m++]=ch; } else { wordID=13; index--; } break; case '-': simbol[m++]=ch; ch=string[index++]; if(ch=='-') { wordID=29; simbol[m++]=ch; } else { wordID=14; index--; } break; case '!': ch=string[index++]; if(ch=='=') { wordID=21; simbol[m++]=ch; } else { wordID=31; index--; } break; case '=': simbol[m++]=ch; ch=string[index++]; if(ch=='=') { wordID=25; simbol[m++]=ch; } else { wordID=18; index--; } break; case '*': wordID=15; simbol[m++]=ch; break; case '/': wordID=16; simbol[m++]=ch; break; case '(': wordID=27; simbol[m++]=ch; break; case ')': wordID=28; simbol[m++]=ch; break; case '{': wordID=5; simbol[m++]=ch; break; case '}': wordID=6; simbol[m++]=ch; break; case ';': wordID=26; simbol[m++]=ch; break; case '\"': wordID=30; simbol[m++]=ch; break; case '#': wordID=0; simbol[m++]=ch; break; case ':': wordID=17; simbol[m++]=ch; break; default: wordID=-1; break; } } simbol[m++]='\0'; }

    运行截图

  • 相关阅读:
    博客园样式设置
    最坏情况为线性时间的选择算法
    棋盘覆盖
    矩阵乘法的Strassen算法及时间复杂度
    大整数乘法及算法时间复杂度
    全排列问题的递归算法(Perm)
    python的lambda
    python的zip函数
    python操作队列
    mysql基础命令
  • 原文地址:https://www.cnblogs.com/hano/p/5967323.html
Copyright © 2011-2022 走看看