回 帖 发 新 帖 刷新版面

主题:哪位大哥帮小弟编个词法分析器好吗~?

明天要交作业拉~
    急死我拉~~
        到现在还没搞出来哦~
             麻烦大哥们拉~[em3][em3][em3][em3][em3][em3][em3][em3][em3]

回复列表 (共8个回复)

沙发

多加分就行 ,啊哈哈哈哈


板凳

编译只有靠自己编,别人帮不了你的,别人只能帮你解决技术上的问题,但真正怎样去做还是要靠你自己

3 楼

那是什么东东

4 楼

楼上的不帮忙就算了,耍什么嘴皮子啊.
不就是词法分析么,源代码如下:
#include <iostream.h>
#include <stdio.h>
#include <string.h>
FILE *f;
void noblank(char &ch)
{
    while (ch==' '||ch=='\n')
        ch=fgetc(f);
}
//====================================================================
void identifier(char name[],char &ch)
{
    int i;
    for (i=0;i<10;i++)
        name[i]='\0';
    i=0;
    name[i]=ch;i++;
    ch=fgetc(f);
    while (('0'<=ch&&ch<='9')||('a'<=ch&&ch<='z')||('A'<=ch&&ch<='Z'))
    {
        name[i]=ch;
        i++;
        ch=fgetc(f);
    }
}
//====================================================================
int intconst(char &ch)
{
    int num=0;
    while ('0'<=ch&&ch<='9')
    {
        num=num*10+(ch-'0');
        ch=fgetc(f);
    }
    return num;
}
//====================================================================
void main()
{
    char ch,name[20];
    char st1[10]={"#include"};
    char st2[10]={"main()"};
    char st3[10]={"{"};
    char st4[10]={"int"};
    char st5[10]={"}"};
    char st6[20]={"cout<<"};
    int num;
    f=fopen("prog.txt","r");
    if (f==NULL)
        cout<<"no such file."<<endl;
    ch=fgetc(f);
    while (!feof(f))
    {
        noblank(ch);
        if ((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
        {
            identifier(name,ch);
            if (!strcmp(name,st1))  printf("${\n");
            else if (!strcmp(name,st2))  printf("$}\n");
            else if (!strcmp(name,st3))  printf("$int\n");
            else if (!strcmp(name,st4))  printf("$cout<<\n");
            else if (!strcmp(name,st5))  printf("$#include\n");
            else printf("$id,%s\n",name);
        }
        else if (ch>='0'&&ch<='9')
        {
            num=intconst(ch);
            printf("$intc,%d\n",num);
        }
        else switch(ch)
        {
            case'(':cout<<"lparen"<<endl;
                ch=fgetc(f);break;
            case')':cout<<"rparen"<<endl;
                ch=fgetc(f);break;
            case'+':cout<<"plus"<<endl;
                ch=fgetc(f);break;
            case'*':cout<<"mult"<<endl;
                ch=fgetc(f);break;
            case';':cout<<"semi"<<endl;
                ch=fgetc(f);break;
            case'=':cout<<"give value"<<endl;
                ch=fgetc(f);break;
            case'.':cout<<"point"<<endl;
                ch=fgetc(f);break;
            default:break;
        }
    }fclose(f);
}

虽说晚了,但看看还是对你有些帮助.

5 楼

。。。。

6 楼

词法分析器不难,不过语法分析器就难了,至少我不知道怎么做,呵呵

7 楼

哦也现在要交语义制导翻译了,写不来.....

8 楼

要做出来简单,要做得好就有难度~!

我来回复

您尚未登录,请登录后再回复。点此登录或注册