sabra baig
sabra baig

Reputation: 11

Program complied with no error , but does not output anything

here is the code below, I am trying to convert infix expression to posfix expression. I am just trying to handle parenthesis case right now, but it does not output any thing, according to my understanding it should output correct post expr for infix3.

#include <iostream>
#include <stack>
#include <ctype.h>
#include <string>
using namespace std;

string I2PConvertor(string exp);
string I2PConvertor(string exp)
{
    stack<int> st;
    string ans;
    for (int i = 0; i < exp.size(); i++) {
        if (isalpha(exp[i])) {
            ans += exp[i];
        }
        else {
            if (st.empty()) {
                st.push(exp[i]);
            }
            else {
                switch (st.top()) {
                case '(':
                    st.push(exp[i]);
                case '+':
                    st.push(exp[i]);
                case ')': {
                    st.pop();
                    while (st.top() != '(') {
                        ans += st.top();
                        st.pop();
                    }
                    st.pop();
                    st.push(exp[i]);
                }
                }
            }
        }
    }
    while (!st.empty()) {
        ans += st.top();
        st.pop();
    }
    return ans;
}

int main()
{
    string infix1 = "a*b+c";
    string infix2 = "a-b*c";
    string infix3 = "(a+b)/c";
    string infix4 = "(a+b)*(c-d)";
    // expected: ab*c+
    //std::cout << I2PConvertor(infix1) << std::endl;
    // expected: abc*-
    //std::cout << I2PConvertor(infix2) << std::endl;
    // expected: ab+c/
    std::cout << I2PConvertor(infix3) << std::endl;
    // expected: ab+cd-*
    // std::cout << I2PConvertor(infix4) << std::endl;
    return 0;
}

Upvotes: 0

Views: 73

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70257

As pointed out in the comments, a case block should, barring exceptional circumstances, be ended with a break statement.

switch (st.top()) {
case '(':
  st.push(exp[i]);
  break;
case '+':
  st.push(exp[i]);
  break;
case ')': {
  ...
  break;
}
}

It's also worth noting that you'll want to do some checks in your ) case that the stack is not empty before checking the top element haphazardously. Unless this is an academic exercise and your teacher promises to only give valid input, there's still the risk of segfault if that case gets hit on an empty stack, so some error checking may be warranted.

Upvotes: 1

Related Questions