C++实现表达式的计算

#include<iostream>
#include<cstring>
#include<string>
#include<sstream>
#include<stack>
#include<map>
#include<cctype>


using namespace std;




string expression;
string post_e;
stack<char> s1;
stack<string> s2;
map<char, int> t1;
map<char, int> t2;


bool isop(string s)
{
if (s == "+" || s == "-" || s == "*" || s == "/")return true;
return false;
}


string cal(int a, int b, char op) {
int ans = 0;
switch (op)
{
case '+': ans = a + b; break;
case '-': ans = a - b; break;
case '*': ans = a*b; break;
case '/':ans = a / b; break;
default:break;
}
stringstream ss;
string an;
ss << ans;
an = ss.str();
return an;
}


int main() {
t1['('] = 1;
t1['+'] = 3;
t1['-'] = 3;
t1['*'] = 5;
t1['/'] = 5;
t1[')'] = 6;
t1['#'] = 0;


t2['#'] = 0;
t2['('] = 6;
t2['+'] = 2;
t2['-'] = 2;
t2['*'] = 4;
t2['/'] = 4;
t2[')'] = 1;

cin >> expression;
expression =expression+ "#";

s1.push('#');
string t;


int len = expression.length();
int i = 0;

while (true) {
if (isdigit(expression[i])) {
t += expression[i++];
}
else {
if (!t.empty()) {
s2.push(t);
t.clear();
}
if (t2[expression[i]] > t1[s1.top()]) {
s1.push(expression[i++]);
}
else if (t2[expression[i]] <= t1[s1.top()]) {
if (s1.top() == '(')s1.pop(), i++;
else if (t1[s1.top()] == t2[expression[i]])break;
else {
string temp(1,s1.top());
s2.push(temp);
s1.pop();
}
}
}
}


stack<string> s3;

while ((s2.size()+s3.size())!=1) {
if (isop(s2.top())) {
s3.push(s2.top());
s2.pop();
}
else {

if (!s2.empty() && !isop(s3.top()) && !isop(s2.top())) {
s2.push(s3.top());
s3.pop();
continue;
}
string p1 = s2.top();
s2.pop();
string p2 = s2.top();
s2.pop();
if (!isop(p1) && !isop(p2)) {
int num2, num1;;
stringstream ss(p1);
ss >> num1;
stringstream ss2(p2);
ss2 >> num2;
s2.push(cal(num2, num1, s3.top()[0]));
s3.pop();
}
else {
s3.push(p1);
s3.push(p2);
}
}
}
cout << s2.top() << endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/PAN_Andy/article/details/60642419