Created
September 7, 2023 06:54
-
-
Save kabeer11000/76ff4629e74339410735873ef9c1ee9c to your computer and use it in GitHub Desktop.
Revisions
-
kabeer11000 created this gist
Sep 7, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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; }