状态机的一种实现方法

看到wiki上关于自动机编程的文章, 其中自动化技术和自动机一节只有伪码, 俺写了个C版本的, 如下
#include <stdio.h>
typedef struct
{
    int state;
    int changed;
    int c;
} state_mach;
enum states {
    before, inside, after
} e_states;
int hop2state(state_fsm *fsm, int state)
{
    fsm->state = state;
    fsm->changed = 1;
    return 1;
}
int setState(state_mach *fsm)
{
    if (fsm->c == '\n')
        return hop2state(fsm, before);
 
    switch(fsm->state) {
    case before:
        if (fsm->c!=' ')
            return hop2state(fsm, inside);
        break;
    case inside:
        if (fsm->c == ' ')
            return hop2state(fsm, after);
        else
            return hop2state(fsm, inside);
        break;
    case after:
        break;
    }
    return 0;
}
int doAction(state_mach *fsm)
{
    switch (fsm->state) {
    case before:
        putchar('\n');
        break;
    case inside:
        putchar(fsm->c);
        break;
    }
    return 0;
}
 
int main()
{
    state_mach fsm = {before, 0, 0};
    while((fsm.c = getchar())!= EOF) {
        if (setState(&fsm)) {
            fsm.changed = 0;
            doAction(&fsm);
        }
    }
}

 

posted on 2014-02-18 13:44  jianglili  阅读(416)  评论(0编辑  收藏  举报

导航