Thursday 15 September 2011

c++ - How to add multi digit integers in a reverse polish calculator -



c++ - How to add multi digit integers in a reverse polish calculator -

// file: calc.h #include <iostream> #include <stack> // uses stl #include <string> // uses stl using namespace std; void evaluate_stack_tops(stack<double> & numbers, stack<char> & operations); double read_and_evaluate(string line) { const char right_parenthesis = ')'; stack<double> numbers; // local stack object stack<char> operations; // local stack object double number; char symbol; size_t position = 0; while (position < line.length()) { if (isdigit(line[position])) { number = line[position++] - '0'; // value numbers.push(number); } else if (strchr("+-*/", line[position]) != null) { symbol = line[position++]; operations.push(symbol); } else if (line[position] == right_parenthesis) { position++; evaluate_stack_tops(numbers, operations); } else position++; } if (!operations.empty()) evaluate_stack_tops(numbers, operations); homecoming numbers.top(); } void evaluate_stack_tops(stack<double> & numbers, stack<char> & operations) { double operand1, operand2; operand2 = numbers.top(); numbers.pop(); operand1 = numbers.top(); numbers.pop(); switch (operations.top()) { case '+': numbers.push(operand1 + operand2); break; case '-': numbers.push(operand1 - operand2); break; case '*': numbers.push(operand1 * operand2); break; case '/': numbers.push(operand1 / operand2); break; } operations.pop(); } // file: use_stack.cpp #include <iostream> using namespace std; #include "calc.h" int main() { double answer; string line; cout << "type parenthesized arithmetic look (single digits only!):\n"; getline(cin, line); reply = read_and_evaluate(line); cout << "that evaluates " << reply << endl; system("pause"); homecoming 0; }

everything works , can input simple things "2 4 3 * + 7 – 2 +" if wanted input "123 60 +" not work. separated in 2 header files. can give me hint on how take multi-digit integers?

one way solve problem find number, instead of assuming 1 digit long, utilize loop collect other digits part of number. loop terminate when encounters non-digit, or space.

a improve way tokenize input string using stringstream. in scenario, set entire line of input string , utilize while loop similar following:

stringstream ss(line); string token; while (ss >> token) { // stuff token }

c++ stack calculator postfix-notation

No comments:

Post a Comment