Skip to content

Instantly share code, notes, and snippets.

@kabeer11000
Created September 7, 2023 06:54
Show Gist options
  • Select an option

  • Save kabeer11000/76ff4629e74339410735873ef9c1ee9c to your computer and use it in GitHub Desktop.

Select an option

Save kabeer11000/76ff4629e74339410735873ef9c1ee9c to your computer and use it in GitHub Desktop.

Revisions

  1. kabeer11000 created this gist Sep 7, 2023.
    71 changes: 71 additions & 0 deletions main.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    #include <iostream>
    #include <sstream>
    #include <stack>
    #include <string>

    // Function implementation, not important for this question
    double Task3Evaluate(const std::string& expression) {
    std::stack<double> operands;

    std::istringstream iss(expression);
    std::string token;

    while (iss >> token) {
    if (isdigit(token[0]) || (token[0] == '-' && token.length() > 1)) {
    // If the token is a number (including negative numbers)
    operands.push(std::stod(token));
    } else {
    // If the token is an operator
    double operand2 = operands.top();
    operands.pop();
    double operand1 = operands.top();
    operands.pop();

    if (token == "+") {
    operands.push(operand1 + operand2);
    } else if (token == "-") {
    operands.push(operand1 - operand2);
    } else if (token == "*") {
    operands.push(operand1 * operand2);
    } else if (token == "/") {
    if (operand2 == 0) {
    throw std::runtime_error("Division by zero is not allowed.");
    }
    operands.push(operand1 / operand2);
    } else {
    throw std::runtime_error("Invalid operator: " + token);
    }
    }
    }

    if (operands.size() != 1) {
    throw std::runtime_error("Invalid expression: " + expression);
    }

    return operands.top();
    }
    // Expression solving calculator, based on the operator-array algorithm I discussed
    void Task3() {
    std::string expression;

    // Input an expression
    std::cout << "Enter an expression: \n";
    std::cin.clear();
    std::cin.ignore();
    std::getline(std::cin, expression); // The problem, this takes the last 'enter' press form the input buffer and so the code executes with basically a blank expression

    try {
    // Evaluate the expression and give a result in double form
    double result = Task3Evaluate(expression);
    std::cout << "Result: " << result << std::endl;
    } catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
    }
    }

    int main() {
    int a;
    std::cin >> a;
    Task3();
    return 0;
    }