Here is the error I get:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
Aborted (core dumped)
I am reading a file that has about 50 lines. Do you see the issue in my code below?
using namespace std;
bool areParenthesesBalanced(const std::string& expr)
{
stack<char> s;
char a, b, c;
for (int i=0; i<expr.length(); i++)
{
if (expr[i]=='(' || expr[i]=='[' || expr[i]=='{')
{
s.push (expr[i]);
}
else
{
switch (expr[i])
{
case ')':
a = s.top();
s.pop();
if (a=='{' || a=='[')
cout<<"Not Balanced";
break;
case '}':
b = s.top();
s.pop();
if (b=='(' || b=='[')
cout<<"Not Balanced";
break;
case ']':
c = s.top();
s.pop();
if (c=='(' || c=='{')
cout<<"Not Balanced";
break;
}
}
}
if (s.empty()) //check if stack is empty
{
return true;
}
else
{
return false;
}
}
int main()
{
std::ifstream t("prog1.cpp");
std::string str;
t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
if(areParenthesesBalanced(str))
{
cout<<"Balanced";
}
else
{
cout<<"Not Balanced";
}
return 0;
}