Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have no output and I am also missing significant logic.

What I have tried:

C++
// Required headers
//  main.cpp
// Program Purpose: Implementing a stack structure in C++.
#include <iostream>
#include <string.h>
#include <bits/stdc++.h>

using namespace std;

int main() {

    // Create a stack of capacity equal to expression size
    stack <float> s;

    cout << "Please enter an expression in Post-fix notation" << endl;
    string exp;

    float val1, val2;

    // set status = false when division by zero
    bool status = true;

    // read each operand / operator
    while (cin >> exp) {

        // If the character is a number, push to stack
        try {
            s.push(stof(exp));

            // operator ==> pop values from stack and do operation
        } catch(...) {

            if (!s.empty()) {
                val1 = s.top();
                s.pop();
            }

            if (!s.empty()) {
                val2 = s.top();
                s.pop();
            } else {
                // stack is empty
                status = false;
            }

            // do only if status == true
            if (status) {
                // arithmetic operation
                if (exp == "+") {
                    s.push(val2 + val1);
                } else if(exp == "-") {
                    s.push(val2 - val1);
                } else if(exp == "*") {
                    s.push(val2 * val1);
                } else if(exp == "/") {
                    if (val1 == 0) {
                        status = false;
                    } else {
                        s.push(val2 / val1);
                    }
                }
            }
        }
    }

    if (status) {
        // final answer is the element present on the stack
        cout<<"Result: "<< s.top();
    } else {
        cout << "error: division by zero" << endl;
    }

    return 0;
}
Posted
Updated 1-Nov-20 20:21pm
v2
Comments
Shao Voon Wong 2-Nov-20 1:09am    
For purpose of your exercise, you can use std::vector to implement your stack. std::vector is a dynamic array that can expand and shrink. STL already has a stack implementation that you can use.

What is your question?

If you can use the STL container then see this : <stack> - C++ Reference[^]
 
Share this answer
 
Including the stack header your code works. In order to see the output you have to send EOF sequence (CTRL+D on Linux, CTRL+Z on Windows).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900