Login Register






Thread Rating:
  • 0 Vote(s) - 0 Average


C++ script that involves classes, templates, and file handling filter_list
Author
Message
C++ script that involves classes, templates, and file handling #1
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

// Templated Stack class
template <typename T>
class Stack {
private:
    T* data;
    int capacity;
    int size;

public:
    Stack(int capacity) : capacity(capacity), size(0) {
        data = new T[capacity];
    }

    ~Stack() {
        delete[] data;
    }

    void push(T value) {
        if (size < capacity) {
            data[size++] = value;
        } else {
            cerr << "Stack overflow!" << endl;
        }
    }

    T pop() {
        if (size > 0) {
            return data[--size];
        } else {
            cerr << "Stack underflow!" << endl;
            return T(); // Return default value for simplicity
        }
    }

    bool isEmpty() const {
        return size == 0;
    }
};

// Function to evaluate a postfix expression
template <typename T>
T evaluatePostfix(const string& expression) {
    Stack<T> stack(20);

    stringstream ss(expression);
    string token;

    while (ss >> token) {
        if (isdigit(token[0])) {
            stack.push(stod(token));
        } else {
            T operand2 = stack.pop();
            T operand1 = stack.pop();

            switch (token[0]) {
                case '+':
                    stack.push(operand1 + operand2);
                    break;
                case '-':
                    stack.push(operand1 - operand2);
                    break;
                case '*':
                    stack.push(operand1 * operand2);
                    break;
                case '/':
                    stack.push(operand1 / operand2);
                    break;
                default:
                    cerr << "Invalid operator: " << token << endl;
                    break;
            }
        }
    }

    return stack.pop();
}

int main() {
    ifstream inputFile("expressions.txt");

    if (!inputFile.is_open()) {
        cerr << "Failed to open the file." << endl;
        return 1;
    }

    string line;
    while (getline(inputFile, line)) {
        cout << "Expression: " << line << endl;
        double result = evaluatePostfix<double>(line);
        cout << "Result: " << result << endl;
        cout << "------------------------" << endl;
    }

    inputFile.close();

    return 0;
}

Explanation:

    The script defines a templated Stack class for managing a stack of values.
    It implements a function to evaluate a postfix expression using the Stack class.
    The main function reads expressions from a file (expressions.txt), evaluates them, and prints the results.

Reply







Users browsing this thread: 1 Guest(s)