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;
    if (!(cin >> n)) return 0;

    State state = State::Idle;

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

        // Rule: Once in Error state, all further commands are ignored.
        if (state == State::Error) {
            continue; 
        }

        // State Transition Logic
        if (state == State::Idle) {
            if (cmd == "start") {
                state = State::Busy;
            }
        } 
        else if (state == State::Busy) {
            if (cmd == "done") {
                state = State::Idle;
            } else if (cmd == "fail") {
                state = State::Error;
            }
        }
        // If cmd doesn't match or state is Error, state remains unchanged.
    }

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

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

3 start done start

Expected Output

Busy