溫馨提示×

如何用C語言switch case構建狀態機

小樊
202
2024-06-13 22:17:47
欄目: 編程語言

在C語言中可以使用switch case語句來構建狀態機。下面是一個簡單的示例:

#include <stdio.h>

typedef enum {
    STATE_IDLE,
    STATE_RUNNING,
    STATE_PAUSED,
    STATE_STOPPED
} State;

int main() {
    State currentState = STATE_IDLE;
    char input;

    while(1) {
        switch(currentState) {
            case STATE_IDLE:
                printf("Currently in idle state. Press 'r' to start running.\n");
                break;
            
            case STATE_RUNNING:
                printf("Currently running. Press 'p' to pause, 's' to stop.\n");
                break;
            
            case STATE_PAUSED:
                printf("Currently paused. Press 'r' to resume, 's' to stop.\n");
                break;
            
            case STATE_STOPPED:
                printf("Currently stopped. Press 'r' to start running again.\n");
                break;
        }

        input = getchar();

        switch(currentState) {
            case STATE_IDLE:
                if(input == 'r') {
                    currentState = STATE_RUNNING;
                }
                break;
            
            case STATE_RUNNING:
                if(input == 'p') {
                    currentState = STATE_PAUSED;
                } else if(input == 's') {
                    currentState = STATE_STOPPED;
                }
                break;
            
            case STATE_PAUSED:
                if(input == 'r') {
                    currentState = STATE_RUNNING;
                } else if(input == 's') {
                    currentState = STATE_STOPPED;
                }
                break;
            
            case STATE_STOPPED:
                if(input == 'r') {
                    currentState = STATE_RUNNING;
                }
                break;
        }
    }

    return 0;
}

在這個示例中,我們定義了一個枚舉類型State來表示狀態機的不同狀態。在主函數中,我們使用一個while循環來不斷檢查當前狀態并根據輸入改變狀態。通過使用switch case語句,我們可以根據當前狀態打印不同的提示信息,并根據輸入來改變狀態。這樣就構建了一個簡單的狀態機。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女