Hi, I'm writing a program that checks parens/brackets/braces if they are paired. Tha catch is I have to write my own stack functions, this is my code so far, it used to work when I was working with just the parentheses, now that I added more options it's not working and now I'm lost, any expert advice or tips from a second pair of eyes? Thanks in advance.
BTW, did I write my initialize() and top() functions correctly?
Thanks again!
/*
This little program checks to see whether the left and right
parentheses / brackets / braces
characters are properly mathed and nested in a line of text.
*/
#include <iostream>
#include <string>
using namespace std;
const unsigned MAX_DEPTH = 4;
struct charStack {
char *paren;
unsigned elements;
} stack;
bool die ( const string& );
void initialize ( charStack& );
bool full ( const charStack& );
bool empty ( const charStack& );
void push ( charStack&, char );
char pop ( charStack& );
char top ( charStack& );
bool isOpen (char);
char isClose (char);
bool balance ( charStack& );
int main () {
string line;
bool ok = true;
initialize ( stack );
cout << "Type a string: ";
if ( !getline ( cin, line ) ) die ( "can't input string." );
for ( unsigned i = 0; i < line.size(); i++ ) {
if ( isOpen(line[i]) )
push( stack, line[i] );
else if ( line[i] = isClose(line[i]) ) {
if ( empty ( stack ) ) {
ok = false;
break;
}
else if (line [i] = top ( stack ))
pop ( stack );
else {
ok = false;
break;
}
}
}
if (!ok || (!empty ( stack ) ) )
cout << "These parens don't match." << endl;
else
cout << "These parens match. HOORAY!!" << endl;
}
bool die ( const string & msg ) {
cerr << endl << "Fatal Error: " << msg << endl;
cin.get();
exit ( EXIT_FAILURE );
}
void initialize ( charStack & stack ) {
char *newParens;
newParens = (char *) malloc(sizeof(char) * MAX_DEPTH);
if (newParens == NULL) {
die ( "Insufficient memory to initialize stack." );
}
stack.paren = newParens;
}
bool full ( const charStack & stack ) {
if ( stack.elements == MAX_DEPTH - 1)
return true;
return false;
}
bool empty ( const charStack & stack ) {
if ( stack.elements == 0 )
return true;
return false;
}
void push ( charStack & stack, char c ) {
stack.paren[stack.elements++] = c;
if(stack.elements > MAX_DEPTH) die ("Stack Overflow");
}
char pop ( charStack & stack ) {
if(stack.elements < 0) die ("These parens don't match.");
return (--stack.elements);
}
char top ( charStack & stack ) {
if ( stack.elements == 0 )
return 0;
return ( stack.elements - 1);
}
bool isOpen (char c) {
return ( c == '(' || c == '[' || c =='{' );
}
char isClose(char c) {
switch (c) {
case')':return'(';
case'}':return'{';
case']':return'[';
}
return '\0';
}