Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define STACK_SIZE 100
- #include <stdio.h>
- char stack[STACK_SIZE];
- int sp;
- /*
- * Pushes character c onto the stack.
- * Returns 0 if successful.
- * Returns -1 if an error occurs. (Stack full).
- */
- int push (char c)
- {
- if ((sp+1)< STACK_SIZE){
- stack[++sp] = c;
- return 0;
- }
- else{
- return -1;
- }
- }
- /*
- * Pops next character off the stack.
- * Returns the char if successful.
- * Returns -1 if an error occurs. (Stack empty).
- */
- int pop ()
- {
- if (sp==0)
- {
- return -1;
- }
- else{
- sp--;
- return stack[sp+1];
- }
- }
- /*
- * Returns the current size of the stack.
- */
- int stackSize()
- {
- return sp;
- // TODO
- }
- /*
- * Tests if the stack is correctly implemented
- */
- int main () {
- int c;
- int value;
- int line;
- int charnum;
- int result;
- line = 1;
- charnum = 0;
- c = getchar();
- while (c != EOF) {
- c = getchar();
- charnum++;
- if (stackSize() == STACK_SIZE) {
- result = 1;
- printf("Error: Stack Full!");
- break;
- }
- if (c == '(' || c == '[' || c == '{') {
- push(c);
- } else if (c == '\n') {
- line++;
- charnum = 0;
- } else if (c == ')' || c == '}' || c == ']') {
- value = pop();
- if (value == '(') {
- value = ')';
- if (c == value) {
- result = 0;
- }
- }
- else if (value == '[') {
- value = ']';
- if (c == value) {
- result = 0;
- }
- }
- else if (value == '[') {
- value = ']';
- if (c == value) {
- result = 0;
- }
- }
- else {
- result = 1;
- printf("Line %d, Char %d: Found %c, expected )", line, charnum, c);
- break;
- }
- } else if (value == '\0') {
- printf("Line %d, Char %d: Found %c. No matching character", line, charnum, c);
- break;
- }
- }
- while (c == EOF) {
- if (pop() == '(') {
- printf("Error: Expecting ), found end of input.");
- } else if (pop() == '[') {
- printf("Error: Expecting ], found end of input.");
- } else if (pop() == '{') {
- printf("Error: Expecting }, found end of input.");
- }
- }
- if (result == 0) {
- printf("Well formatted input.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement