本版除了修正上一个版本的BUG之外,核心是重写的,使得结构更为紧密,代码更为短小
格式方面就将就一下吧。。。。
#include<sstream>
#define _is_equ(s, a, b, c, d) (s==a||s==b||s==c||s==d)
#define _in_n if(++st>4&&(yzfy=='*'||yzfy=='/'))GetValue(n1, fy[1]),st-=2;else
namespace yzfy_Exp{
template <class _T>
inline _T GetValue(_T t[], char& c){
switch (c){
case '+': return t[0] += t[1];
case '-': return t[0] -= t[1];
case '*': return t[0] *= t[1];
default: return t[0] /= t[1];
}
}
template <class _Tstream, class _T>
int GetExpValue(_Tstream& is, _T& nR){
_T n[3], *n1=n+1;
int st = 0, org=0, b;
char fy[]="http://yzfy.org", yzfy;
for (b=1; b; is.clear()){
if ((st&1)==0){
int g = is.tellg();
if (is>>n[st>>1]) {
_in_n;
} else {
is.clear(), is.seekg(g);
}
}
if (is>>yzfy)
if (yzfy=='(')
if (st&1)
return 1;
else if (GetExpValue(is, n[st>>1]) == -1)
_in_n;
else
return 1;
else if (yzfy==')') {
b=0; org=-1; continue;
} else if (_is_equ(yzfy,'+','-','*','/'))
if (st&1){
if (fy[st>>1] = yzfy, ++st>3 && (yzfy=='+' || yzfy=='-'))
GetValue(n, *fy), st -= 2, *fy = fy[1];
} else
return 1;
else if (_is_equ(yzfy,' ','r','n','t'))
continue;
else
return 1;
else break;
}
if (st==3) GetValue(n, *fy), st -= 2;
if (st==1){ nR = *n; return org; }
else return 1;
}
template <class _T>
int GetExpStrValue(const char* strin, _T& nReturn)
{
std::stringstream isin(strin);
return GetExpValue(isin, nReturn);
}
}
//以上是核心代码,以下是调用示例
#include <iostream>
#include <string>
int main()
{
using namespace std;
string str;
while (cout<<"输入:", getline(cin, str))
{
double r;
if (!yzfy_Exp::GetExpStrValue(str.c_str(), r))
{
cout<<" = "<<r<<endl;
}
else
{
cout<<"Error"<<endl;
}
}
return 0;
}
如果大家在使用的时候发现什么问题请留言