Question: Im writing a C program that reads in a .txt file that contains multiple lines of parenthesis and checks whether each line is balanced. I
Im writing a C program that reads in a .txt file that contains multiple lines of parenthesis and checks whether each line is balanced. I have the code compling and running but it's not validating each line correctly. It says each line is valid when there are lines that are not valid. Also, the first line of the .txt file says how many lines there are and the program should skip over that line I just don't know how to do that. Here is my code so far:
/******************************************************** *Name: Patrick McEldowney * *Date: 1/31/17 * *Assignemtnt: Project 1 - Sequence and Order validation* ********************************************************* *This program takes an expression and checks to see if * *its parenthesis are balanced or not. It reads the * *expressions from a tezt file./ * ********************************************************/ #include
int top = -1; char stack[100]; /*Function Definitions*/ void push(char); char pop(); void find_top();
/***************************************************** *Description: This is the main function that reads in* *the file and calls the other functions. * *****************************************************/ void main() { FILE * fp; fp = fopen("expressions.txt", "r"); int i; char exp[100], t; while(fgets(exp, 100, fp)) { for(i = 0; exp[i] != '\0'; i++) { if(exp[i] == '(' ||exp[i] == '{' || exp[i] == '[') { push(exp[i]); } else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']') { t = pop(); if(t == '(' && exp[i] == ')' || t == '{' && exp[i] == '}' || t == '[' && exp[i] == ']') { continue; } } } printf(" %s ",exp); find_top(); } }
/******************************************************** *Description: Pushs the element to the top of the stack.* *Inout: The char to push to the stack. * *Output: None. * ********************************************************/ void push(char exp) { stack[top] = exp; top++; }
/************************************************************* *Description: Pop the top elements off the top of the stack. * *Inout: None * *Output: None * *************************************************************/ char pop() { if(top == -1) { printf("Expression is invalid "); exit(0); } else { return stack[top--]; // returning top to the stack } }
/************************************************* *Description: Finds the top elements in the stack* *************************************************/ void find_top() { if(top == -1)//check if expression is balanced or not printf("Expression is valid "); else printf("Expression is invalid "); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
