求字符串表达式(不含括号)的值
数字分离
运算符优先级+-*/
只需一个字符串栈,保存数字和运算符
#include<iostream> #include<stack> #include<sstream> #include<string> using namespace std; template<class out_T,class in_T> out_T convert(const in_T &t){ stringstream ss; out_T result; ss<<t; ss>>result; return result; } double calc(string aa,string op,string bb){ double a=convert<double>(aa); double b=convert<double>(bb); if(op=="+") return a+b; if(op=="-") return a-b; if(op=="*") return a*b; if(op=="/") return a/b; } bool isdigit(char s){ int a=s-‘0‘; if(a>=0 && a<=9) return true; return false; } int main(){ string s; string x,y; string op; double tmp; int priv[300]; priv[‘+‘]=priv[‘-‘]=2; priv[‘*‘]=priv[‘/‘]=1; // priv[‘(‘]=10; while(cin>>s){ stack<string> num; int len=s.size(); int start=0; string str; char last=0; for(int i=0;i<len;i++){ if(isdigit(s[i])){ start=i; for(;i+1<len && (isdigit(s[i+1]) || s[i+1]==‘.‘);i++); str=s.substr(start,i-start+1); num.push(str); } else if(s[i]==‘-‘ && (last==0 || last==‘(‘)){ num.push("0.0"); num.push("-"); } else if(priv[s[i]]>0){ while(priv[s[i]]==2 && num.size()>2){ y=num.top(); num.pop(); op=num.top(); num.pop(); x=num.top(); num.pop(); tmp=calc(x,op,y); num.push(convert<string>(tmp)); } num.push(convert<string>(s[i])); } else continue; last=s[i]; } while(num.size()>2){ x=num.top(); num.pop(); op=num.top(); num.pop(); y=num.top(); num.pop(); if(op=="-" || op=="/") tmp=calc(y,op,x); else tmp=calc(x,op,y); num.push(convert<string>(tmp)); } cout<<convert<double>(num.top())<<endl; } return 0; }
原文:http://www.cnblogs.com/AndyJee/p/4908006.html