68. State Machine with Enums

#include <iostream>
#include <string>
using namespace std;

enum class State { Idle, Busy, Error };

const char* toString(State s) {
    switch (s) {
        case State::Idle:  return "Idle";
        case State::Busy:  return "Busy";
        case State::Error: return "Error";
    }
    return "";
}

int main() {
    int n;
    cin >> n;

    State state = State::Idle;

    for (int i = 0; i < n; ++i) {
        string cmd;
        cin >> cmd;

        if (cmd == "start" && state == State::Idle) {
            state = State::Busy;
        } else if (cmd == "done" && state == State::Busy) {
            state = State::Idle;
        } else if (cmd == "fail" && state == State::Busy) {
            state = State::Error;
        }
        
        // other inputs/state combos are ignored (no transition)
    
    }

    cout << toString(state);
    return 0;
}

 

Solution Details

  • The enum State defines three possible states: Idle, Busy, Error.
  • The system starts in Idle.
  • Input commands update the state:
    • "start" → Idle → Busy
    • "done" → Busy → Idle
    • "fail" → Busy → Error
  • The final state is printed using toString(State).
     

Significance for Embedded Developers

  • Many firmware components (UART drivers, tasks, protocols) follow finite state machines (FSMs).
  • Using enums makes states explicit instead of hidden behind integers.
  • Helps in designing predictable, maintainable control flows.

     
Loading...

Input

3 start done start

Expected Output

Busy