0

以下是一个实现 DFA(确定性有限自动机)的简单程序。但是,我的问题不涉及 DFA。

#include<iostream>
using namespace std;

int main()
{
    char c;
    int state=1;
    while((c=cin.get())!='4')
    {
        switch(state)
        {
            case 1:
            if(c=='0')
            state=2;
            if(c=='1')
            state=1;
            if(c=='2')
            state=2;

            break;

            case 2:
            if(c=='0')
            state=5;
            if(c=='1')
            state=1;
            if(c=='2')
            state=3;

            break;

            case 3:
            if(c=='0')
            state=1;
            if(c=='1')
            state=5;
            if(c=='2')
            state=4;

            break;

            case 4:
            if(c=='0')
            state=3;
            if(c=='1')
            state=4;
            if(c=='2')
            state=5;

            break;

            case 5:
            if(c=='0')
            state=5;
            if(c=='1')
            state=4;
            if(c=='2')
            state=1;

            break;

            default:
            cout<<"Input will not be accepted"<<endl;

        } //switch
        cout<<"Current state is "<<state<<endl; 
    } //while


    return 0;
}

当我运行代码时,我发现每一行都被输出了两次。例如,当我输入 0 1 0 0 4 时,DFA 从状态 1->2->1->2->5 进入,因此输出应该是:

Current state is 2
Current state is 1
Current state is 2
Current state is 5

但输出是:

Current state is 2
Current state is 2
Current state is 1
Current state is 1
Current state is 2
Current state is 2
Current state is 5
Current state is 5

谁能指出原因?

4

2 回答 2

5

cin.get()读取一个字符,因此您也在读取空格。然后在每个空格之后,您的程序只会输出先前的状态,因为空格不匹配任何内容。你想cin >> c改用。

于 2013-01-26T20:04:46.290 回答
1

由于您显然不打算将代码发布到 CodeReview,所以让我发布一个替代方案,而不是我认为我会如何编写代码:

#include<iostream>
using namespace std;

static const int states[][3] = {
    { 2, 1, 2 },
    { 5, 1, 3 },
    { 1, 5, 4 },
    { 3, 4, 5 },
    { 5, 4, 1 }
};

int main()
{
    char c;
    int state=1;
    while(cin >> c && c != '4') {
        if (c >= '0' && c <= '2')
            state = states[state-1][c-'0'];
        else
            std::cout << "Input will not be accepted.\n";
        cout<<"Current state is "<<state<<"\n"; 
    }
    return 0;
}

至少对我来说,这似乎更容易阅读和理解,更不用说将状态机本身与读取字符并根据输入遍历状态的代码分开。

于 2013-01-27T01:45:47.047 回答