In: Computer Science
My output is not working correctly its telling me things aren't balanced when it should be telling me they are balanced. I cannot figure out where I went wrong.
here is the input.txt:
{{[a]b}[]([c])}
[]}b[]([])(}[
[][[{a}{b}{c}]]
({{[x]}([[[[[a]]]b]])c}[])
{{{{{{{{{a}}}}}}}}
{[}]
[[}[abc]{]]
[{{}()()([])}[}]]
{a}{{[a[[{(a)}]]]}}
[[({a[]})b]{}[({c[]}d)]]
#include <iostream>
#include <stack>
#include <fstream>
#include <string>
using namespace std;
bool isbalanced(string exp) {
stack<char> mystack;
char x;
for (int i = 0;i < exp.length(); i++)
{
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[') {
mystack.push(exp[i]);
}
if (mystack.empty())
return false;
switch (exp[i]) {
case ')':
x = mystack.top();
mystack.pop();
if (x == '{' || x == '[')
return false;
break;
case '}':
x = mystack.top();
mystack.pop();
if (x == '(' || x == '[')
return false;
break;
case ']':
x = mystack.top();
mystack.pop();
if (x == '(' || x == '{')
return false;
break;
}
}
return (mystack.empty());
}
int main() {
ifstream inputfile;
string exp;
inputfile.open("input.txt");
while (getline(inputfile, exp)) {
if (isbalanced(exp)) {
cout<<exp<<"the expression is balanced. \n";
}
else{
cout<<exp<<"the expression is not balanced. \n";
}
}
return 0;
}
C++ code
#include <iostream>
#include <stack>
#include <fstream>
#include <string>
using namespace std;
bool isbalanced(string exp) {
stack<char> mystack;
char x;
for (int i = 0;i < exp.length(); i++)
{
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[') {
mystack.push(exp[i]);
continue;
}
if (mystack.empty())
return false;
switch (exp[i]) {
case ')':
x = mystack.top();
mystack.pop();
if (x == '{' || x == '[')
return false;
break;
case '}':
x = mystack.top();
mystack.pop();
if (x == '(' || x == '[')
return false;
break;
case ']':
x = mystack.top();
mystack.pop();
if (x == '(' || x == '{')
return false;
break;
}
}
return (mystack.empty());
}
int main() {
ifstream inputfile;
string exp;
inputfile.open("input.txt");
while (getline(inputfile, exp)) {
if (isbalanced(exp)) {
cout<<exp<<"the expression is balanced. \n";
}
else{
cout<<exp<<"the expression is not balanced. \n";
}
}
return 0;
}
sample output