I was trying to write this code for converting infix expression to postfix expression but I'm getting a segmentation fault for some values. Code is :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
#include <bits/stdc++.h>
using namespace std;
int prec(char ch){
if(ch=='^')
return 3;
else if(ch=='*' || ch=='/')
return 2;
else if(ch=='+' || ch=='-')
return 1;
else
return 0;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
stack <char> st;
string s;
cin>>s;
for(int i=0;i<21;i++){
if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z'))
cout<<s[i];
else{
if( st.empty())
st.push(s[i]);
else if( s[i]=='(' || prec (s[i])> prec(st.top()))
st.push(s[i]);
else if( s[i]==')'){
while(st.top()!='(')
{cout<<st.top(); st.pop();}
st.pop();
}
else{
while(prec(st.top())>=prec(s[i]))
{
cout<<st.top(); st.pop();
}
}
}
}
return 0;
}
For smaller expressions, it gives an answer but for an expression like a+b*(c^d-e)^(f+g*h)-i it gives segmentation fault.
for(int i=0;i<s.size();i++)in order to avoid that?toporpopan emptystd::stack. And under no circumstances should you hop on pop.s[i]>='a' && s[i]<='z'->std::islower(s[i])and so on. Don't give up portability for no reason. Or do the whole lot in one go withstd::isalpha