0

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.

5
  • 3
    Iterating fixed 21 times regardless of the length of string looks a bad idea. Commented Oct 22, 2020 at 19:05
  • Why not using for(int i=0;i<s.size();i++) in order to avoid that? Commented Oct 22, 2020 at 19:08
  • Thou shalt not top or pop an empty std::stack. And under no circumstances should you hop on pop. Commented Oct 22, 2020 at 19:08
  • What did the debugger tell you? Commented Oct 22, 2020 at 19:41
  • 1
    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 with std::isalpha Commented Oct 22, 2020 at 20:02

1 Answer 1

2

Firstly, the iteration should be just in the strings.

This means that

for(int i=0;i<21;i++){

should be

for(int i=0;i<s.size();i++){

Secondly, you forgot to check if the stack is empty in the loop.

This means that

while(prec(st.top())>=prec(s[i]))

should be

while(!st.empty() && prec(st.top())>=prec(s[i]))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.