Advertisement
Guest User

david kill me

a guest
Nov 18th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. #define STACK_SIZE 100
  2. #include <stdio.h>
  3.  
  4. char stack[STACK_SIZE];
  5. int sp;
  6.  
  7.  
  8. /*
  9. * Pushes character c onto the stack.
  10. * Returns 0 if successful.
  11. * Returns -1 if an error occurs. (Stack full).
  12. */
  13. int push (char c)
  14. {
  15. if ((sp+1)< STACK_SIZE){
  16. stack[++sp] = c;
  17. return 0;
  18. }
  19. else{
  20. return -1;
  21. }
  22. }
  23.  
  24.  
  25. /*
  26. * Pops next character off the stack.
  27. * Returns the char if successful.
  28. * Returns -1 if an error occurs. (Stack empty).
  29. */
  30. int pop ()
  31. {
  32. if (sp==0)
  33. {
  34. return -1;
  35. }
  36. else{
  37. sp--;
  38. return stack[sp+1];
  39. }
  40. }
  41.  
  42. /*
  43. * Returns the current size of the stack.
  44. */
  45. int stackSize()
  46. {
  47. return sp;
  48. // TODO
  49. }
  50.  
  51. /*
  52. * Tests if the stack is correctly implemented
  53. */
  54. int main () {
  55. int c;
  56. int value;
  57. int line;
  58. int charnum;
  59. int result;
  60. line = 1;
  61. charnum = 0;
  62. c = getchar();
  63. while (c != EOF) {
  64. c = getchar();
  65. charnum++;
  66. if (stackSize() == STACK_SIZE) {
  67. result = 1;
  68. printf("Error: Stack Full!");
  69. break;
  70. }
  71. if (c == '(' || c == '[' || c == '{') {
  72. push(c);
  73. } else if (c == '\n') {
  74. line++;
  75. charnum = 0;
  76. } else if (c == ')' || c == '}' || c == ']') {
  77. value = pop();
  78. if (value == '(') {
  79. value = ')';
  80. if (c == value) {
  81. result = 0;
  82. }
  83. }
  84. else if (value == '[') {
  85. value = ']';
  86. if (c == value) {
  87. result = 0;
  88. }
  89. }
  90. else if (value == '[') {
  91. value = ']';
  92. if (c == value) {
  93. result = 0;
  94. }
  95. }
  96. else {
  97. result = 1;
  98. printf("Line %d, Char %d: Found %c, expected )", line, charnum, c);
  99. break;
  100. }
  101. } else if (value == '\0') {
  102. printf("Line %d, Char %d: Found %c. No matching character", line, charnum, c);
  103. break;
  104. }
  105. }
  106. while (c == EOF) {
  107. if (pop() == '(') {
  108. printf("Error: Expecting ), found end of input.");
  109. } else if (pop() == '[') {
  110. printf("Error: Expecting ], found end of input.");
  111. } else if (pop() == '{') {
  112. printf("Error: Expecting }, found end of input.");
  113. }
  114. }
  115. if (result == 0) {
  116. printf("Well formatted input.");
  117. }
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement