3

I have to write a function that accepts a string and returns a bool. The string passed in is a series or different parenthesis opened or closed ex.({[]}) and returns whether the 'parens' are well-balanced. This has to be implemented by adding items to a stack. I am getting the following error:

parenMatching_demo.cpp:18:12: error: no match for 'operator==' in 'c == '('

The psudocode is:

matcher(expression) 
    for each character in expression 
        if  the character is an opener
            push on stack
        else if the character is a closr
            if stack is empty return false
            if the (opener at) the top of the stack does not match the closer
                return false
            pop the stack

     if the stack is not empty return false
     return true

This is what I have.

template <typename T>   
bool parenMatching(string c) {
    stack<string> s;
    for (int i = 0; i < s.size(); i++) {
        if (c == '(' || c == '[' || c == '{' || c == '<')
            s.push(c);
        else if (c == ')' || c == ']' || c == '}' || c == '>') {
            if (s.empty()) return false;
            if (s.top() != '(' || s.top() != '[' || s.top() != '{' || s.top() != '<')
                return false;
            s.pop();
        }
    }
}
Rapptz
  • 20,807
  • 5
  • 72
  • 86
FJam
  • 736
  • 3
  • 13
  • 32

2 Answers2

9

One problem is the type of the stack, it should be

stack<char> s;

Then the for loop, the condition should be

i < c.size()

The next problem is

if (c == '(' || c == '[' || c == '{' || c == '<')

does not compare the character of the string c at i, so you need

const char c2 = c[i];
if (c2 == '(' || c2 == '[' || c2 == '{' || c2 == '<')

If you need help to fix the rest, let me/us know :)

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
2

You're comparing a string with a char in your codes that check for the parentheses. You're missing a line where you get the current character you're looking at as you iterate your string - you probably want something like:

char current = c.at(i);

Additionally, you need to fix your stack type as Daniel Frey says in his answer.

edit - he's since changed his to contain this info, so that answer should have everything you need.

TomD
  • 166
  • 8