以下是一个实现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&gt; 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
有谁可以指出原因?
答案 0 :(得分:5)
cin.get()
读取一个字符,因此您也在阅读空格。然后在每个空格之后,程序只输出先前的状态,因为空间不匹配任何东西。您想要使用cin >> c
。
答案 1 :(得分: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;
}
至少在我看来,这似乎更容易阅读和理解,更不用说将状态机本身与读取字符的代码分开,并根据输入遍历状态。