Question
I've written an C++ program to check if an string expression enter by the user is balanced eg: (2+(2)). My program runs and checks for
I've written an C++ program to check if an string expression enter by the user is balanced eg: (2+(2)).
My program runs and checks for input such as {} however does not return the correct value when input such as {a} are entered.
This is my code, I can't seem to find the issue with my algorithm.
HEADER FILE
#ifndef BALANCED_H #define BALANCED_H
#include
class Balanced { public: Balanced(std::string); bool isBalanced(); bool isMatch(char c, char d);
private: std::string expression; };
#endif // BALANCED_H
IMPLEMENTATION FILE
#include "Balanced.h" #include
Balanced::Balanced(std::string s) : expression(s) { }
bool Balanced::isBalanced() { std::stack
for(unsigned int i=0; i < expression.size(); i++) { if(expression[i]=='{'|| expression[i] == '[' || expression[i] == '(') { b.push(expression[i]); continue; }
if(b.empty() || !isMatch(b.top(), expression[i])) { return false; }
else{ b.pop(); } } return b.empty();
}
bool Balanced::isMatch(char c, char d) { if(c == '{' && d == '}') { return true; } else if(c == '[' && d == ']') { return true; }
else if(c == '(' && d == ')') { return true; }
else { return false; } }
MAIN
#include
void displayHelp();
int main() { std::string s; std::string expression;
std::cout<<"Welcome to balance expression program" < do{ std::cout<<"Enter any key to continue or type 'Help' to display a help menu "; std::cout<<"You may also type 'Exit' to exit the program: "; std::cin>>s; if(s=="Help") { displayHelp(); continue; } else if(s=="Exit") { break; } else{ std::cout<<"Enter an expression: "; std::cin>>expression; } Balanced d(expression); if(d.isBalanced()!=true){ std::cout<<"The expressions is not balanced"; std::cout< else{ std::cout<<"The expression is balanced"; std::cout< }while(s!="Exit"); return 0; } void displayHelp() { std::cout< #include void displayHelp(); int main() { std::string s; std::string expression; std::cout<<"Welcome to balance expression program" < do{ std::cout<<"Enter any key to continue or type 'Help' to display a help menu "; std::cout<<"You may also type 'Exit' to exit the program: "; std::cin>>s; if(s=="Help") { displayHelp(); continue; } else if(s=="Exit") { break; } else{ std::cout<<"Enter an expression: "; std::cin>>expression; } Balanced d(expression); if(d.isBalanced()!=true){ std::cout<<"The expressions is not balanced"; std::cout< else{ std::cout<<"The expression is balanced"; std::cout< }while(s!="Exit"); return 0; } void displayHelp() { std::cout<
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started