We’re supposed to implement a program to check whether the braces, brackets and parens in a given expression all match using a stack structure in C++ for my CS class. Unfortunately, I’m kinda stuck on this one, since I keeps telling me something doesn’t match, even when it most decidedly does.
Here’s what I got so far:
#include <stdlib.h>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
struct cell {int value; cell* next; };
cell* top;
int numElem;
void init()
{
top = NULL;
numElem = 0;
}
int pop()
{
int res;
if (top != NULL)
{
res = top -> value;
top = top -> next;
numElem--;
} else {
cout << "FAIL: Stack empty!\n";
res = -1;
}
return res;
}
void push(int element)
{
cell* cat = new cell;
cat -> value = element;
cat -> next = top;
top = cat;
}
void match(char expr[])
{
bool pass = true;
char expected;
char encountered;
char closing;
for (int i=0; pass && (i<strlen(expr)); i++)
{
if ((i==40)||(i==91)||(i==123))
push(i);
else
{
if (i==41)
expected = 40;
if (i==93)
expected = 91;
if (i==125)
expected = 123;
encountered = pop();
if (expected != encountered)
closing = i;
pass = false;
}
}
if (pass)
cout << "Parentheses match OK!\n";
else
cout << encountered << " has opened, but closing " << closing;
cout << " encountered!\nParentheses do not match\n";
}
int main(int argc, char * argv[])
{
init();
match(argv[1]);
return 0;
}
Since the stack framework existed from a previous exercise and worked fine there, I’m strongly assuming whatever error there is should be in void match
In your match function you should test characters, not their indices:
Also you did not update counter in your push: