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?
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 usecin >> cinstead.