C++ help

Discussion in 'General Computer Support' started by nastykae, Sep 20, 2006.

  1. nastykae

    nastykae

    Joined:
    Sep 20, 2006
    Messages:
    1
    Likes Received:
    0
    Hie guys can anyone compile a program for the following:

    Write a program that calculates all valid expressions scientifically using the two-stack algorithm.

    Assumptions :
    All + , - , * , /,(,), $ symbols and numbers are seperated by at least one space (except the digits of a given number)

    End of the expression is marked by a $

    No unary operator is entered

    Example1:

    4 * 7 / ( 6 * 5 - 2 * ) - 12 $

    Answer= 11

    I have come up with the following template for this program but it needs modification so please help:

    #include <iostream>
    #include <string>
    using namespace std;




    template <class T>
    class stack
    {
    private: T *x;
    int top;
    int size;
    public:
    stack(int);
    ~stack();
    void push( const T&);
    void pop(T&);
    void show();
    bool empty();
    bool full();
    };

    template <class T>
    stack<T>::stack(int s)
    {
    top = -1;
    size= s-1;
    x= new T;
    }

    template <class T>
    stack<T>::~stack()
    {
    delete [] x;
    }

    template <class T>
    void stack<T>::push(const T &ele)
    {
    x[++top]=ele;
    }

    template <class T>
    bool stack<T>::empty()
    {
    return top==-1;
    }

    template <class T>
    bool stack<T>::full()
    {
    return top == size ;
    }

    template <class T>
    void stack<T>::pop(T &ele)
    {
    ele= x[top--];
    }

    stack<string> s2(3);
    stack<double> s1(4);


    void calc()

    {
    while(!s2.empty())
    {
    string op;
    s2.pop(op);
    double n1, n2, res;
    s1.pop(n2);
    s1.pop(n1);
    if(op=="+")
    res=n1+n2;
    else
    if(op=="-")
    res=n1-n2;
    else
    if(op=="*")
    res=n1*n2;
    if(op=="/")
    res=n1/n2;
    s1.push(res);
    }
    }

    int main()
    {
    char token[80];
    string s=" ";
    cin>>token;
    while (token[0] != '$')
    {
    if(isdigit(token[0]))
    {
    cout<<token;
    cout<<": is a number\n";
    double t= atof(token);
    s1.push(t);
    }
    else
    {
    s=token[0];
    cout<<s;
    cout<<":is an operator\n";
    s2.push(s);
    }

    cin>>token;

    }

    calc();
    double Ans;
    s1.pop(Ans);
    cout<<"Exp value="<<Ans<<"\n";
    return 0;

    }
     
    nastykae, Sep 20, 2006
    #1
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.