码迷,mamicode.com
首页 > 其他好文 > 详细

Compiler_词法分析_表驱动法

时间:2014-05-18 09:11:43      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:compiler

本文出自:http://blog.csdn.net/svitter
DFA:

bubuko.com,布布扣

使用了表驱动法;


构造的表如下:

表驱动

num . E +/- other
0 1 6 - - -
1 1 2 5 - -
2 2 - 3 - -
3 - - - 4 --
4 5 - - - -
5 5 - - - -
6 2 - - - -
7









 


代码如下:
//============================================================================
// Name        : compliler.cpp
// Author      : Vit
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <cstdio>
#include <string.h>
#include <stdlib.h>

using namespace std;

int State[8][5];

//set final accept
const bool Acsta[7] = {0, 1, 1, 0, 0, 1, 0,};

//JudgeNum
int JudgeNum(char &ch)
{
    if(ch >= ‘0‘ && ch <= ‘9‘)
        return 0;
    else if(ch == ‘.‘)
        return 1;
    else if(ch == ‘E‘)
        return 2;
    else if(ch == ‘+‘ || ch == ‘-‘)
        return 3;
    else
        return 4;
}
//init the table
void init()
{
    //set error state
    for(int i = 0; i < 8; i++)
        for(int j = 0; j < 5; j++)
        {
            State[i][j] = 7;
        }

    //set table
    State[0][0] = 1;
    State[0][1] = 6;
    State[1][0] = 1;
    State[1][1] = 2;
    State[1][2] = 5;
    State[2][0] = 2;
    State[2][2] = 3;
    State[3][3] = 4;
    State[4][0] = 5;
    State[5][0] = 5;
    State[6][0] = 2;
}

//利用函数调用来读
char* Judge(char *str)
{
    int i, j;//work point

    //var
    int len = strlen(str);//计算串长度
    char *t = new char[2000];//返回串
    int cur;//字符下标
    char ch;//字符
    int state;//状态
    int beg;//开始
    int endd;//结束

    //start
    for(i = 0; i < len; i++)
    {
        beg = cur = i;
        ch = str[i];
        state = 1;
        endd = beg;
        while(state != 7)
        {
            state = State[state][JudgeNum(ch)];
            ch = str[++cur];
            if(Acsta[state])
                endd = cur;//记录最后一次符合状态的下标
        }
        if(endd != beg)
        {
            if((endd - beg) > strlen(t))
            {
                for(j = beg; j < endd; j++)
                {
                    t[j-beg] = str[j];
                }
            }
        }
    }
    return t;
}


int main (void)
{
    char *t;
    char str[2000];
    init();
    freopen("test", "r", stdin);
    while(~scanf("%s", str))
    {
        t = Judge(str);
        printf("%s\n", t);
    }
    return 0;
}


Compiler_词法分析_表驱动法,布布扣,bubuko.com

Compiler_词法分析_表驱动法

标签:compiler

原文地址:http://blog.csdn.net/svitter/article/details/25981185

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!