#include #include #include FILE *fptr; char line1[10000]; int floor_number; int flag_a; int char_zero_cross; enum states{ START, PROCESS, } state; enum events{ START_LOOP, INCREMENT, DECREMENT, ERROR_EVENT }; void step_state(enum events event){ switch(state){ case START: switch(event){ case START_LOOP: state = PROCESS; break; default: exit(1); break; } break; case PROCESS: switch(event){ case INCREMENT: floor_number++; break; case DECREMENT: floor_number--; break; case ERROR_EVENT: printf("ERROR!\n"); exit(1); break; default: exit(1); break; } } } int main() { flag_a = 0; floor_number = 0; fptr = fopen("2015_day_1_input.txt", "r"); if(fptr == NULL) { printf("Not able to open the file."); } fgets(line1, 10000, fptr); fclose(fptr); step_state(START_LOOP); size_t i = 0; while (line1[i] != '\0'){ if (line1[i] == '('){ step_state(INCREMENT); } else if (line1[i] == ')'){ step_state(DECREMENT); } else{ printf("\nCharacter not ( or ), ERROR!"); exit(1); } i++; if (floor_number < 0 && flag_a == 0){ printf("first zero-crossing is at position %lu\n", i); flag_a = 1; } } printf("\nThe Floor number is: %d\n\n", floor_number); return 0; } //Sources: //https://dev.to/zirkelc/how-to-iterate-over-c-string-lcj#:~:text=Pointer-,For%2DLoop,each%20iteration%20with%20*%2B%2Bp%20. //https://yakking.branchable.com/posts/state-machines-in-c/