Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <stack>
- #include <string>
- #include <cctype>
- #include <cmath>
- using namespace std;
- stack <char> ParenthesisStack;
- stack <int> NumberStack;
- void printStack(stack <char> ParenthesisStack) {
- while (!ParenthesisStack.empty())
- {
- cout << " " << ParenthesisStack.top();
- ParenthesisStack.pop();
- }
- cout << endl;
- }
- void evaluatePostFix(string n)
- {
- for (int i = 0; i<n.length(); i++) {
- if(n[i] == ' ' || n[i] == ',')
- continue;
- else if (isdigit(n[i]))
- {
- int operand = 0;
- while(isdigit(n[i]))
- {
- operand = (operand*10) + (n[i] - '0');
- i++;
- }
- i--;
- NumberStack.push(operand);
- }
- else
- {
- int val1 = NumberStack.top(); NumberStack.pop();
- int val2 = NumberStack.top(); NumberStack.pop();
- if(n[i] == '+')
- cout << val1 + val2 << endl;
- else if(n[i] == '-')
- cout << val1 - val2 << endl;
- else if(n[i] == '*')
- cout << val1 * val2 << endl;
- else if(n[i] == '/')
- cout << val1 / val2 << endl;
- else if(n[i] == '^')
- cout << pow(val1, val2) << endl;
- else cout<<"Unexpected Error" << endl;
- }
- }
- }
- int evaluateInFix(int num1, int num2)
- {
- return 0;
- }
- void checkParenthesis(string n)
- {
- for (int i = 0; i<n.length(); i++) {
- if (n[i] == '(' || n[i] == '[' || n[i] == '{') {
- ParenthesisStack.push(n[i]);
- cout << "pushing" << endl;
- }
- else if (n[i] == ')' || n[i] == ']' || n[i] == '}') {
- if (ParenthesisStack.empty()) {
- cout << "Stack Empty" << endl;
- }
- else {
- ParenthesisStack.pop();
- cout << "popping" << endl;
- }
- }
- else {
- continue;
- }
- }
- printStack(ParenthesisStack);
- }
- void checkString(string n)
- {
- bool isOperator = false;
- for (int i = 0; i<n.length(); i++)
- {
- if (n[i] == ' ' || n[i] == ',')
- continue;
- else if (n[i] == '+' || n[i] == '-' || n[i] == '/' || n[i] == '*' || n[i] == '^')
- {
- cout << "operator" << " ";
- }
- else if (isdigit(n[i]))
- {
- while(isdigit(n[i]))
- {
- i++;
- if(n[i] == '+' || n[i] == '-' || n[i] == '/' || n[i] == '*')
- {
- isOperator = true;
- }
- }
- cout << "integer" << " ";
- if (isOperator == true)
- {
- cout << "operator" << " ";
- isOperator = false;
- }
- }
- }
- cout << endl;
- }
- int main() {
- string n;
- cout << "Enter mathematical calculation string: ";
- getline(cin, n);
- checkParenthesis(n);
- checkString(n);
- evaluatePostFix(n);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement