The below program has no compile or link error, but there is a possibility that there is logic error. Can you see any error? This is my assignment for data structure.
The topic is somthing like this: ask user to key in a string, and see whether the brackets are balanced.
/*Parentheses, brackets, and braces are symbols used to enclose
expressions. For example, in arithmetic we may enclose an expression
inside parentheses to indicate its higher precedence*/
#include<stack>
#include<iostream>
using namespace std;
int main ()
{
std::stack <char> braceStack;
char firstChar,i;
int top=-1;
cout<<"Please enter characters of an mathematical expression with brackets to represent the order of operations being done(z to stop)\n";
cout<<"==========\n";
cout<<"enter the character one at a time(z to stop)...";
cin>>i;
firstChar=i;
if(i=='z') cout<<"The stack is empty.\n";
else
{
do
{
if(i=='('){
braceStack.push(i);
top++;
}
else if (i==')'&& braceStack.empty()){
cout<<"error! This expression is wrongly written\n";
top++;
}
else if ((i==')')==braceStack.top()){
braceStack.pop(); //Pop the top brace when they are compatible
top++;
}
cout<<"Continue entering the character(z to stop)...";
cin>>i;
}
while (i!='z');
}
if(!braceStack.empty())
cout<<"Error! This expression is wrongly written.\n";
else if (braceStack.empty()&&firstChar!='z')
cout<<"The brackets are balanced.\n";
return 0;
}