词法分析程序<一>

来源:互联网 发布:新加坡方便面yum 编辑:程序博客网 时间:2024/05/15 08:09
<pre name="code" class="cpp">
#include "stdio.h"#include<stdlib.h>#include "conio.h"#include "string.h"#include "ctype.h"char save[20];/*定义暂存函数*/char *p;char count[200];int total;char *sum[5]={"begin","end","integer","program","var"};/*定义5个关键字*/char alpha()/*分析标识符*/{ int i,j;  char *opp;  i=0;  j=0;/*j=0是标识符,j=1是关键字*/ /* while(isalpha(*p))/*检查是否是字母*/ { save[i]=*p;   p++;i++;   }*/  while(isalnum(*p))/*检查是字母还是数字,如果是字母返回1,是数字返回2*/ { save[i]=*p;   p++;i++; }  opp=save;  for(i=0;i<5;i++)/*把字母与关键字表核对,如果是关键字就设置j=1*/    if(!(strcmp(opp,sum[i])))/*比较两个字符串*/    { printf(" %d  keyword  %s\n",total,opp); /*识别关键字*/  j=1;    }  if(j==0) printf(" %d  captionsign  %s\n",total,opp); /*识别标识符*/  p--; /*回退多读进的字符*/ return 0;} char digit()/*分析数字*/{ int i;  i=0;  while(isdigit(*p))/*检查是否数字(0-9)*/{ save[i]=*p;  i++;p++; }  printf(" %d  digit  %s\n",total,save);  p--;  return 0;}int main(){ //int i,j;  total=1;/*计数器等于一*/  memset(count,0,200);/*把count所指内存区域的前200个字节设置成字符0*/   strcpy(count,"program test;\nvar i,j:integer;\nbegin i:=j+1;end.- * /");//事先存储输入   printf("The source program is:\n");  puts(count);  printf("\n");  p=count;  while(*p!='\0')/*检查源程序是否结束*/    { memset(save,0,20);   while(*p==' '||*p=='\n'||*p=='\t')p++;/*检查是否是空白字符,如果是直接跳过*/      if(isalpha(*p)) alpha();/*识别关键字或标识符*/        else if(*p==';')           printf(" %d  boundarysign   %c\n",total,*p);          else if(*p==',')               printf(" %d  boundarysign  %c\n",total,*p);             else if(*p==':')    {p++;     if(*p=='=')  printf(" %d  airthmeticsign  %s\n",total,":=");/*识别赋值号*/           else  { printf(" %d error %s\n",total,":");/*识别冒号*/                     p--; /*回退多读进字符*/  }    }   else if(*p=='+')                      printf(" %d  arithmeticsign  %c\n",total,*p);      else if(*p=='-')                      printf(" %d  arithmeticsign  %c\n",total,*p);     else if(*p=='*')                      printf(" %d  arithmeticsign  %c\n",total,*p);     else if(*p=='/')                      printf(" %d  arithmeticsign  %c\n",total,*p);                                               else if(*p=='.')                         printf(" %d  boundarysign  %c\n",total,*p);                         else if(*p=='(')                              printf(" %d  boundarysign  %c\n",total,*p);                             else if(*p==')')                                printf(" %d  boundarysign  %c\n",total,*p);            else if(isdigit(*p))/*识别整数*/                                                 digit(); else  printf(" %d error %s\n",total,*p);     total=total+1;p++;  /*准备识别下一个单词*/  }  printf("\npress any key to return");  getch();  return 0;}


                                             
0 0
原创粉丝点击