| #include #include #include #include "demo.h" #define SIZE 100 char stack[SIZE]; int bottom = 0, top = 0; void push(char ch) { if (top != SIZE) { stack[top] = ch; top++; } } char pop() { if (top != bottom) { top--; stack[top] = '/0'; return stack[top]; } return -2; } int get_id(FILE *fp) { char temp[100]; int id; fscanf(fp, "%d", &id); fgets(temp, 100, fp); return id; } void translate(int id, char *a) { switch(id) { case 0: *a = '#'; break; case 12: *a = 'i'; break; case 22: *a = '+'; break; case 23: *a = '-'; break; case 24: *a = '*'; break; case 21: *a = '/'; break; } } bool is_terminate(char ch) { if (ch == 'i' || ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '#') return true; return false; } void trans(char ch, char a, int *i, int *j) { switch (ch) { case 'E': *i = 0; break; case 'e': *i = 1; break; case 'T': *i = 2; break; case 't': *i = 3; break; case 'F': *i = 4; break; case 'A': *i = 5; break; case 'M': *i = 6; break; } switch (a) { case 'i': *j = 0; break; case '+': *j = 1; break; case '-': *j = 2; break; case '*': *j = 3; break; case '/': *j = 4; break; case '(': *j = 5; break; case ')': *j = 6; break; case '#': *j = 7; break; } } void search_table(char ch, char a) { int i, j; trans(ch, a, &i, &j); char temp[20] = {'/0'}; strcpy(temp, TABLE[i][j]); if (strcmp(temp, "~") == 0) { pop(); return; } else if (strcmp(temp, "") != 0) { pop(); for (unsigned ii = 0; ii < strlen(temp); ii++) { push(temp[ii]); } return; } else { printf("Error!/n"); exit(0); } } void main() { FILE *in; int id = 0; char a = 0; in = fopen("result.txt", "r"); push('#'); push('E'); id = get_id(in); translate(id, &a); while (true) { if (is_terminate(stack[top-1])) { if (stack[top-1] == a && a == '#') { printf("success./n"); return; } else if (stack[top-1] == a) { pop(); id = get_id(in); translate(id, &a); } else { printf("Error!/n"); return; } } else if (!is_terminate(stack[top-1])) { search_table(stack[top-1], a); } } fclose(in); } |