Reputation: 3423
Following is a simple program which implements a DFA(deterministic finite automata). However, my problem does not involve 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;
}
When I ran the code, I found that every line was being output twice. For, example when I entered 0 1 0 0 4, the DFA goes from state 1->2->1->2->5 and thus output should be:
Current state is 2
Current state is 1
Current state is 2
Current state is 5
But the output is:
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
Can anyone point out the cause?
Upvotes: 0
Views: 93
Reputation: 490808
Since you're apparently not going to post your code to CodeReview, let me post an alternative of how I think I'd write the code:
#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;
}
At least to me, this seems easier to read and understand, not to mention separating the state machine itself from the code that reads characters and walks through the states based on the input.
Upvotes: 1
Reputation: 3066
cin.get()
reads one character, so you are also reading spaces. Then after each space your program just outputs previous state because space doesn't match anything. You want to use cin >> c
instead.
Upvotes: 5