字符串转化为数学表达式并求值(后缀表达式)

主要用到后缀表达式和利用后缀表达式求值。

#include<iostream>
#include<string>
#include<cmath>
#include<stack>
#include<map>
#include<vector>

using namespace std;

class Convert
{
public:
	Convert(string tot) :test(tot) {};
	void init() {
		pri["("] = 0;
		pri[")"] = 1;
		pri["*"] = pri["/"] = 2;
		pri["+"] = pri["-"] = 3;
	}
	int tomath() {
		int len = test.size();
		int i;
		init();
		string tem;
		string last="a";
		for (i = 0;i < len;i++) {
			if (test[i] <= '9'&&test[i] >= '0')
				tem += test[i];
			else {
				if(tem!="")
					postfix.push_back(tem);
				tem = "";
				last[0] = test[i];
				deal(last);
			}
		}
		if(tem!="")
			postfix.push_back(tem);
		while (!sign.empty()) {
			postfix.push_back(sign.top());
			sign.pop();
		}
		return calculate(postfix);
	}
	int calculate(vector<string> postfix) { // using stack 
		stack<int> tem;
		int src1, src2;
		vector<string>::iterator iter;
		for (iter = postfix.begin();iter != postfix.end();iter++) {
			if (check(*iter))              // if it is a num ,push 
				tem.push(stringtonum(*iter));
			else {
				src2 = tem.top();
				tem.pop();
				src1 = tem.top();
				tem.pop();
				tem.push(cal(src1, src2, *iter));
			}
		}
		return tem.top();
	}
	int cal(int src1, int src2, string tem) {              // + - * /
		if (tem == "*")
			return src1*src2;
		else if (tem == "/")
			return src1 / src2;
		else if (tem == "+")
			return src1 + src2;
		else
			return src1 - src2;
	}
	int check(string tem) {                       //check if it is a number
		if (tem == "*" || tem == "/" || tem == "+"||tem == "-")
			return 0;
		return 1;
	}
	void deal(string tem) {                         // sign to push
		if (sign.empty())
			sign.push(tem);
		else {
			if (!pri[tem])                            //means (
				sign.push(tem);
			else if (pri[tem] == 1) {
				while (!sign.empty()&&sign.top() != "(") {
					postfix.push_back(sign.top());
					sign.pop();
				}
				sign.pop();
			}
			else if (pri[sign.top()] > pri[tem])
				sign.push(tem);
			else {
				while (!sign.empty()&&pri[sign.top()] <= pri[tem]&&pri[sign.top()]) {
					postfix.push_back(sign.top());
					sign.pop();
				}
				sign.push(tem);
			}
		}
	}
	int stringtonum(string source) {                    // conver string to num
		int num = 0;
		int len = source.size();
		int i;
		for (i = 0;i < len;i++) {
			num = num * 10;
			num = num + source[i] - '0';
		}
		return num;
	}


private:
	string test;
	map<string, int> pri;
	stack<string> sign;
	vector<string> postfix;

};

int main()
{
	string test = "16/4+2*(88/4/11-1)*(2+10)";
	Convert A(test);
	cout << A.tomath() << endl;
	system("Pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值