-3

This code is supposed to convert a given postfix expression to a prefix expression,i was experimenting with the string object in c++ but I don't have enough experience to figure out the problem

I think there's an issue in the push() function

Note:I haven't used the stack header file and implemented the stack using array

here's the code

#include <bits/stdc++.h>
#include <iostream>
#define MAX 5

using namespace std;

class stack1
{
private:
    int stackTop,expTop;
    string stack[MAX],expression;

public:
    stack1()
    {
     stackTop = -1;
        for (int i = 0; i < MAX; i++)
        {
            stack[i] = " ";
        }
    
        getexp();
        check(expression);
        display();
    }
    string pop();
    void push(string expr);
    void display();
    bool isempty();
    bool isfull();
    string combo(string optr1,string optr2,string opr);
    void getexp();
    void check(string expre);
    bool isOperator(string ch);
};

//-----------Gets Expression From User------------------------------------------
void stack1::getexp()
{
    cout<<"Enter the Postfix Expression"<<endl;
    cin>>expression;
    expTop=expression.length()-1;
    
}

void stack1::check(string expre)
{
    string ch;
    int i=0;
    while(expre[i]!=(expre.length()-1))
    {
        ch=expre[i];

        if(isOperator(ch))
        {
            push(combo(pop(),ch,pop()));
        }
        else
        {
            push(ch);
        }
    }
    
}

/*
-------------------------------------------------------------------
    Inputs:
    takes 2 values from the stack which will be operands
    either as single characters or whole strings,these
    values will be passed as optr1 and opttr2,it will
    also take operators such as +,-,* etc.. as char.
    these will be passed in place of opr.

    working:
    combines all the passed values into a single string
    into the following format

    ( optr1 opr optr2 )

    and finaly returns this string
----------------------------------------------------------------------
*/

string stack1::combo(string optr1, string optr2, string opr)
{
    string expr;
    
    expr="("+optr1+opr+optr2+")";
    return expr;
}

/*
------------------------------------------------------------------------
    Working:
    pops the top value from the stack
    and returns it.
    decrements the top pointer
    and initializes the poped element to " "
-------------------------------------------------------------------------
*/
string stack1 ::pop()
{
    string x;
    if (isempty())
    {
        cout << endl
             << "The stack1 is empty" << endl;
    }
    x=stack [stackTop];
    stack [stackTop] = " ";
    stackTop--;
    return x;
}

void stack1 ::push(string expr)
{
    stackTop++;
    stack [stackTop] = expr;
}

bool stack1 ::isempty()
{
    if  (stackTop == -1)
        return true;
    else
        return false;
}

bool stack1 ::isfull()
{
    if  (stackTop == MAX - 1)
        return true;
    else
        return false;
}

bool stack1::isOperator(string ch)
{
    if (ch[0] == '*' || ch[0] == '/' || ch[0] == '+' || ch[0] == '-' || ch[0] == '^')
        return true;
    else return false;
}

void stack1::display()
{
    cout<<"Infix:\t"<<stack[0]<<endl;
}

int main()
{
    stack1 obj;
    return 0;
}
  • 2
    Did you use a debugger to step through your code and observe what it does? What did you find? – CherryDT Oct 02 '22 at 10:06
  • 3
    I'd argue that the first problem is [`#include `](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). – Some programmer dude Oct 02 '22 at 10:09
  • I am Fairly new to coding and i tried what you said,still i am not getting the desired result – Janardhan Polle Oct 02 '22 at 10:10
  • Also, the constructor of a class should be used to *initialize* the object, nothing more. If you need to perform actions, then do it as separate functions that are called by the user of the class and objects, not in the constructor itself. – Some programmer dude Oct 02 '22 at 10:11
  • That your code `stack1::pop` detects an empty stack, then just marches on and "pops" from nothing anyway is evidence you need to explain a few things to [the rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging). Have you ever noticed the standard library stack `pop` method doesn't return a value? Ever wonder why? – WhozCraig Oct 02 '22 at 10:12
  • @Someprogrammerdude should I use string.h ?? – Janardhan Polle Oct 02 '22 at 10:12
  • 2
    What problem see you having with the code? What is the input? What is the expected output? What happens instead? – Alan Birtles Oct 02 '22 at 10:12
  • Not `` which is the header for C string functions. Rather `` for the `std::string` class. – Some programmer dude Oct 02 '22 at 10:15
  • @AlanBirtles The indput is any Postfix expression like AB+ and the output should be (A+B) .Im not getting any output,the programs just takes the input and exits – Janardhan Polle Oct 02 '22 at 10:20
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jesper Juhl Oct 02 '22 at 12:55

1 Answers1

0

Besided the obvious hard bug with #include <bits/stdc++.h> which is not part of C++ (and does not even compile on my machine), you have 2 semantic bugs in your code, which lead to a problem.

Additionally you have a design problem leading to an only partially solution.

And, maybe a misunderstanding of the terms and meaning of "string" and "character"

Example: The string "hello" consists of 5 characters: 'h', 'e', 'l', 'l', 'o'

If you use a std::string and initialize it with "hello" (which is of type const char[6]), the the constructor of the std::string will convert your character array to a std::string, containing the following characters at indices:

index  character
  0       'h' 
  1       'e' 
  2       'l' 
  3       'l' 
  4       'o' 
  5       '\0' 

In your "check" function in line while(expre[i]!=(expre.length()-1)) you access expre[i] which is a character (for example an 'a') and compare it to the length of the std::string "expre". This can of course not work.

The while loop will never terminate. "i" is always the same and you will push always the first character of the input string onto the stack, unti it is full and you get an exception. You should add an overflow-check in your push function.

Additionally, you use a wrong parameter sequence in/with your "combo" function.

If you modify the while loop like the below, then at least this part will work.

    string ch;
    int i = 0;
    //while (expre[i] != (expre.length() - 1))
    while (i != (expre.length()))
    {
        ch = expre[i];

        if (isOperator(ch))
        {
            push(combo(pop(), pop(),ch));
        }
        else
        {
            push(ch);
        }
        ++i;
    }

Now you can successfully convert "abcd+^" to "(a^(b(c+d)))".

But still, it will not work fully.

Additionally:

  • You should use your constructor only to initialize your class.
  • Please use characters where appropriate and not full std::strings

The whole design needs to be reworked.

Because: basically you are creating an infix and not a prefix expression.

Hence, for learning purposes look at here

A M
  • 14,694
  • 5
  • 19
  • 44