fork download
  1. #include <stdio.h>
  2.  
  3. // กำหนดค่าของแต่ละสถานะ
  4. typedef enum {
  5. STATE_INITIAL,
  6. STATE_RUNNING,
  7. STATE_STOPPED,
  8. STATE_ERROR
  9. } State;
  10.  
  11. // ฟังก์ชั่นสำหรับเปลี่ยนสถานะของเครื่อง
  12. void transition(State *state, char input) {
  13. switch (*state) {
  14. case STATE_INITIAL:
  15. if (input == 'S') {
  16. *state = STATE_RUNNING;
  17. printf("Transitioning to RUNNING state.\n");
  18. } else {
  19. *state = STATE_ERROR;
  20. printf("Error! Invalid input.\n");
  21. }
  22. break;
  23. case STATE_RUNNING:
  24. if (input == 'P') {
  25. *state = STATE_STOPPED;
  26. printf("Transitioning to STOPPED state.\n");
  27. } else if (input == 'S') {
  28. *state = STATE_RUNNING;
  29. printf("Already in RUNNING state.\n");
  30. } else {
  31. *state = STATE_ERROR;
  32. printf("Error! Invalid input.\n");
  33. }
  34. break;
  35. case STATE_STOPPED:
  36. if (input == 'S') {
  37. *state = STATE_RUNNING;
  38. printf("Transitioning to RUNNING state.\n");
  39. } else if (input == 'P') {
  40. *state = STATE_STOPPED;
  41. printf("Already in STOPPED state.\n");
  42. } else {
  43. *state = STATE_ERROR;
  44. printf("Error! Invalid input.\n");
  45. }
  46. break;
  47. case STATE_ERROR:
  48. printf("Machine is in ERROR state. Cannot transition further.\n");
  49. break;
  50. }
  51. }
  52.  
  53. int main() {
  54. // เริ่มต้นเครื่องในสถานะ STATE_INITIAL
  55. State currentState = STATE_INITIAL;
  56. char input;
  57.  
  58. printf("Machine is starting...\n");
  59.  
  60. // ทำงานในลูปจนกว่าจะเกิด error
  61. while (currentState != STATE_ERROR) {
  62. printf("Current state: ");
  63. switch (currentState) {
  64. case STATE_INITIAL: printf("INITIAL\n"); break;
  65. case STATE_RUNNING: printf("RUNNING\n"); break;
  66. case STATE_STOPPED: printf("STOPPED\n"); break;
  67. default: break;
  68. }
  69.  
  70. printf("Enter command (S: Start, P: Stop): ");
  71. scanf(" %c", &input); // รับค่าจากผู้ใช้
  72.  
  73. transition(&currentState, input); // เปลี่ยนสถานะตามคำสั่งที่รับ
  74. }
  75.  
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Machine is starting...
Current state: INITIAL
Enter command (S: Start, P: Stop): Error! Invalid input.