c++ - 输出冗余

标签 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;
}

当我运行代码时,我发现每一行都被输出了两次。例如,当我输入 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

谁能指出原因?

最佳答案

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

关于c++ - 输出冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14541014/

相关文章:

c++ - Xcode 10.3 构建失败 “Undefined symbols for architecture x86_64”

c++ - 解析参数值字符串并将值(字符串类型)链接到变量(特定类型)

c++ - 循环内控制台中的输入和输出

c++ - 如何在 C++ (UNIX) 中完全阻止用户输入

c++ - C++ cout和cin执行错误: main.cpp: In function ‘int main()’

c++ - 为什么 g++ 在编译时给我冲突错误?

c++ - 降雨量统计

c++ - 基于模板的动态数据类型选择

c++ - 如何使 c++ 使用 cin 可选?

c++ - 如何将值输入到已经定义的数组中?