This is my code to convert infix expression to postfix. In the last if else condition, if I am using else
then I am getting Segmentation Fault (SIGSEGV)
while if I use else if
and define the if
condition, then the code is working absolutely fine. I cannot figure out why is this happening. This is for the test case (a+(b*c))
. Logically, I have covered a-z,A-Z,(,) previously in the if-else conditions and the code should work fine if I use else
for the operators. I need help here.
#include <bits/stdc++.h>
using namespace std;
int prt(char s)
{
if (s == '(')
return 0;
if (s == '+' || s == '-')
return 1;
if (s == '*' || s == '/')
return 2;
if (s == '^')
return 3;
}
int main()
{
// your code goes here
int T;
cin >> T;
while (T--) {
string str;
cin >> str;
stack<char> s;
for (int i = 0; i <= str.length(); i++) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
cout << str[i];
}
else if (str[i] == '(') {
s.push('(');
}
else if (str[i] == ')') {
while (s.top() != '(') {
cout << s.top();
s.pop();
}
s.pop();
}
else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/' || str[i] == '^') { //This One
while (prt(s.top()) >= prt(str[i])) {
cout << s.top();
s.pop();
}
s.push(str[i]);
}
}
while (!s.empty()) {
cout << s.top();
s.pop();
}
cout << endl;
}
return 0;
}
Also, some feedback on code writing style improvement is appreciated.