输出中的冗余

Avi*_*mar 0 c++ cin

以下是一个实现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;
}
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,我发现每行输出两次.例如,当我输入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
Run Code Online (Sandbox Code Playgroud)

但输出是:

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
Run Code Online (Sandbox Code Playgroud)

有谁可以指出原因?

jko*_*era 5

cin.get()读取一个字符,所以你也在阅读空格.然后在每个空格之后,程序只输出先前的状态,因为空间不匹配任何东西.你想要cin >> c改用.