I am trying to solve this problem that finds if an expression has matching grouping symbols or not:
Write a program that takes as input an arithmetic expression. The program outputs whether the expression contains matching grouping symbols. For example, the arithmetic expressions {25 + (3 - 6) * 8} and 7 + 8 * 2 contains matching grouping symbols. However, the expression 5 + {13 + 7) / 8 -2 *9 does not contains matching grouping symbols.
So far, i have written this code using stacks and strings.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
void matchingSymbol(string);
int main()
{
matchingSymbol("{25+(3-6)*8}"); //match
matchingSymbol("7+(8*2"); //no match
string input;
cout << "Enter an arithemtic to check for matching grouping symbols: ";
cin >> skipws >> input;
matchingSymbol(input);
}
void matchingSymbol(string arithInput)
{
stack<char> tempStr;
for (int i = 0; i < arithInput.length(); i++) {
if (arithInput.at(i) == '{' || arithInput.at(i) == '(' || arithInput.at(i) == '[') {
tempStr.push(arithInput.at(i));
}
else if (!tempStr.empty() && (arithInput.at(i) == '}' && tempStr.top() == '{' || arithInput.at(i) == ')' && tempStr.top() == '(' || arithInput.at(i) == ']' && tempStr.top() == '[') ){
cout << "Popped for arithInput: " << arithInput.at(i) << " and tempStr: " << tempStr.top() << "\n";
tempStr.pop();
}
}
if (tempStr.empty()) {
cout << arithInput << " --> " << "Groupings matched.\n";
}
else {
cout << arithInput << " --> " << "Groupings not matched.\n";
}
}
Output:
Popped for arithInput: ) and tempStr: (
Popped for arithInput: } and tempStr: {
{25+(3-6)*8} --> Groupings matched.
7+(8*2 --> Groupings not matched.
Enter an arithemtic to check for matching grouping symbols: 1+[1}]
Popped for arithInput: ] and tempStr: [
1+[1}] --> Groupings matched.
I am running into an issue where input such as 1+[1}] would pass as grouped, but obviously isn't. I have a condition in the else if statement that says: I pop from tempStr if and only if a closing character is the complementary to the top element in the opening character stack. In the case of 1+[1}], i read the character } and check that the topmost in stack is [. The program shouldn't pop from tempStr yet it is.
Note: an empty tempStr stack means that the expression is grouped properly.
I have tried to change my conditions and refactor them and track all the variables but I can't see the flaw in my logic. It would be great if you can help me pinpoint why input such as 1+[1}] is passing as grouped, yet it isn't.
so far, this is the most efficient logic i have come up with:
pseudocode else if (stack not empty AND (closing symbol is read AND top on stack is its complementary)) {
pop stack
}