1

So i have this reverse polish notation program i have to do for class which ask the user for a postfix expression .

for example the user would input a b + c d - * , the program at the end converts it into

((a + b) * (c - d)) But this is not my problem.

So my question is how do you push a b + c d - * which is one whole string, one element at a time into a stack. Professor also said the input has a space between each element when it is stored in the string.

the output would look like a b + c d - * taking up one stack.

I need it to be a b + c d - * taking up 7 stacks.

There was some basic code in class I'm using as a skeleton to write the program, If possible would like to modify it to fit what I need.

#include <iostream>
#include <string>

using namespace std;

typedef string stack_element;

class stack_node
{
    public:
    stack_element data;
    stack_node *next;
};

class stack
{
    public:
    stack();
    ~stack();
    stack_element & top();
    void pop();
    void push(const stack_element &);
    void print();

    private:
    stack_node *s_top;
};

stack::stack()
{
    s_top=0;
    cout<<"Inside Default Constructor\n";
}

void stack::push(const stack_element & item)
{
    cout<<"Inside push \n";
    stack_node *p = new stack_node;

    p->data = item;
    p->next = 0;

    if (s_top == 0)
    {
        s_top = p;
    }
    else
    {
        p->next = s_top;
        s_top = p;
    }
}

int main()
{
    string input;
    cout<<"enter an input:";
    cin>>input;
    S.push(input);
}
Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
Ron
  • 21
  • 1
  • 4
  • 2
    [Split the string](http://stackoverflow.com/q/236129/478288) and then iteratively push each element independently. – chrisaycock Oct 28 '13 at 17:54
  • doing so at the momment – Ron Oct 28 '13 at 17:57
  • I'm looking at the example with 124 hits, has the line string str("Split me by whitespaces"); in it. It's the easiest for me to understand will that be the most suited to what I'm doing compared to the other examples? – Ron Oct 28 '13 at 18:07

1 Answers1

1

Is this what you are after?

int main()
{
    string input;
    cout<<"enter an input:";
    while (cin>>input)
    {
        S.push(input);
    }
}

Explanation:

cin >> input reads whitespace delimited characters into input. The return value of the expression is cin. In a boolean context, such as the while loop test, cin is tested to see if the last read failed. The last read will have failed when the input has been consumed, so the loop will terminate.

What text book are you using for your class?

Adam Burry
  • 1,904
  • 13
  • 20