fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. char stack[100][10];
  6. int top = -1;
  7. int pos = 0;
  8. char input[100];
  9.  
  10. void push(const char *s) {
  11. if (top < 99)
  12. strcpy(stack[++top], s);
  13. else
  14. printf("Stack overflow!\n");
  15. }
  16.  
  17. void pop() {
  18. if (top >= 0)
  19. top--;
  20. }
  21.  
  22. void printStack() {
  23. for (int i = 0; i <= top; i++) printf("%s", stack[i]);
  24. printf("\n");
  25. }
  26.  
  27. void skipWhitespace() {
  28. while (input[pos] == ' ') pos++;
  29. }
  30.  
  31. int reduce() {
  32. if (top >= 2 &&
  33. strcmp(stack[top - 2], "E") == 0 &&
  34. strcmp(stack[top - 1], "+") == 0 &&
  35. strcmp(stack[top], "E") == 0) {
  36. pop(); pop(); pop();
  37. push("E");
  38. return 1;
  39. }
  40.  
  41. if (top >= 2 &&
  42. strcmp(stack[top - 2], "E") == 0 &&
  43. strcmp(stack[top - 1], "*") == 0 &&
  44. strcmp(stack[top], "E") == 0) {
  45. pop(); pop(); pop();
  46. push("E");
  47. return 1;
  48. }
  49.  
  50. if (top >= 2 &&
  51. strcmp(stack[top - 2], "(") == 0 &&
  52. strcmp(stack[top - 1], "E") == 0 &&
  53. strcmp(stack[top], ")") == 0) {
  54. pop(); pop(); pop();
  55. push("E");
  56. return 1;
  57. }
  58.  
  59. if (top >= 0 && islower(stack[top][0]) && stack[top][1] == '\0') {
  60. pop();
  61. push("E");
  62. return 1;
  63. }
  64.  
  65. return 0;
  66. }
  67.  
  68. int main() {
  69. printf("Enter an Expression: ");
  70. fgets(input, sizeof(input), stdin);
  71. input[strcspn(input, "\n")] = '\0';
  72.  
  73. while (input[pos] != '\0') {
  74. skipWhitespace();
  75. if (input[pos] == '\0') break;
  76.  
  77. char temp[2] = {input[pos], '\0'};
  78.  
  79. if (islower(input[pos]) || input[pos] == '+' || input[pos] == '*' || input[pos] == '(' || input[pos] == ')') {
  80. push(temp);
  81. pos++;
  82.  
  83. printf("Shift: ");
  84. printStack();
  85.  
  86. while (reduce()) {
  87. printf("Reduce: ");
  88. printStack();
  89. }
  90. } else {
  91. printf("Invalid character: %c\n", input[pos]);
  92. return 1;
  93. }
  94. }
  95.  
  96. if (top == 0 && strcmp(stack[0], "E") == 0)
  97. printf("String Accepted\n");
  98. else
  99. printf("String Rejected\n");
  100.  
  101. return 0;
  102. }
  103.  
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
Enter an Expression: String Rejected