1022 词法分析程序

#include<stdio.h>
#include<string.h>
int n,p,zbm;
char ch,code[1000],str[100];
void scaner();
void main()
{
    printf("Please input the source code:\n\n");
    p=0;
    do{
        ch=getchar();
        code[p++]=ch;
    }while(ch!='#');
    printf("\n\nOutput the code:\n\n");
    p=0;
    do{
        scaner();
        if(zbm==98)printf("%s",str);
        else if(zbm==99)printf("<error,%s>",str);
        else printf("<%d,%s>",zbm,str); 
    }while(zbm!=0);
    printf("\n\n");
}
void scaner()
{
    do{
        ch=code[p++];
    }while(ch==' ');
    n=0;
    if((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')||ch=='_')
    {
        while((ch>='0'&&ch<='9')||(ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')||ch=='_')
        {
            str[n++]=ch;
            ch=code[p++];
        }
        str[n++]='\0';
        if     (strcmp(str,"begin")==0)zbm=1;
        else if(strcmp(str,"if"   )==0)zbm=2;
        else if(strcmp(str,"then" )==0)zbm=3;
        else if(strcmp(str,"while")==0)zbm=4;
        else if(strcmp(str,"do"   )==0)zbm=5;
        else if(strcmp(str,"end"  )==0)zbm=6;
        else                           zbm=10;
        p--;
    }
    else if(ch>='0'&&ch<='9')
    {
        zbm=11;
        while((ch>='0'&&ch<='9')||(ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')||ch=='_')
        {
            if(ch<'0'||ch>'9')zbm=99;
            str[n++]=ch;
            ch=code[p++];
        }
        str[n++]='\0';
        p--;
    }
    else
    {
        switch(ch)
        {
            case '+':zbm=13;str[n++]=ch; break;
            case '-':zbm=14;str[n++]=ch; break;
            case '*':zbm=15;str[n++]=ch; break;
            case '/':zbm=16;str[n++]=ch; break;
            case ':':zbm=17;str[n++]=ch;    
                if(code[p]=='=')
                {    zbm=18;str[n++]=ch;}break;
            case '<':zbm=20;str[n++]=ch;    
                if(code[p]=='=')
                {    zbm=21;str[n++]=ch;}break;
                if(code[p]=='>')
                {    zbm=22;str[n++]=ch;}break;
            case'>':zbm=23;str[n++]=ch;    
                if(code[p]=='=')
                {    zbm=24;str[n++]=ch;}break;
            case '=':zbm=25;str[n++]=ch; break;
            case ';':zbm=26;str[n++]=ch; break;
            case '(':zbm=27;str[n++]=ch; break;
            case ')':zbm=28;str[n++]=ch; break;
            case '#':zbm=0 ;str[n++]=ch; break;
            case'\n':zbm=98;str[n++]=ch; break;
            case'\t':zbm=98;str[n++]=ch; break;
            default :zbm=99;str[n++]=ch;
        }
        str[n++]='\0';
    }
}

 

posted @ 2015-10-22 12:16  35陈泽展  阅读(232)  评论(0编辑  收藏  举报