一个计算四则表达式的模板
在9月8日那天我特意编写的,给大家分享的,[4[5h is%v{.v一个很方便的函数模板,可以并且只可以计算含括号的四则表达式x/Eg b5drhe:X~@
只有一个函数接口:int GetExpValue(_Tstream& istrin, _T& nReturn)
参数解释:F/Dj[*DG?F3Q
istrin: 一个输入流,可以是标准IO流,可以是文件流,也可以是串流
nReturn:用于接收计算结果的变量,计算所使用的类型由这个变量确定5f%Fr)M7oG:t
返回值:
返回非0表示计算成功,0表示计算失败有错误h%h#Dj;tx
程序代码:
%hNTY9j @
namespace fy_Exp{di Kk&Z
namespace {template <class _T>DY O0pS]-m;dO
inline _T GetExpValue(_T t[], char& csym){d-npmb0h7HlJy0E
char c=csym; csym=0;
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];//case '/':*yV$}.M;V1|p C{H
}
}}(cq:b:h&_.jgd
template <class _T, class _Tstream>
/* _Tstream: inputstream, _T: get return value
* Return nonzero if get value successfully */
int GetExpValue(_Tstream& istrin, _T& nReturn){
_T t[3] = {0}; //雨中飞燕之作9DK%Vt^0Wu~2u
char csym[3] = "++";
int nLevel = 1, nERR = 0;
if(!(istrin>>t[1]))istrin.clear();
for(;;){Lw0cC&]?s2~a
if(istrin>>csym[2]){X W*[q(L P2s
switch(csym[2]){y^d(p%b'w(].zhV
case '(':
if(!csym[1]){nLevel=0x100; nERR=1;}else
if(!GetExpValue(istrin, t[2]))nLevel|=0x10;
else{nLevel=0x100; nERR=1;}
break;
case ')':xx2qC@$NW
{nLevel = 0x100;}break;
case '+':case '-':case '*':case '/':
{csym[nLevel++] = csym[2];}break;
case ' ':case '\r':case '\n':case '\t':continue;N4E2xQ-Rt"?(l
default:
{nLevel=0x100; nERR=1;}U5C.f;E}"U
}
if(nLevel==0x100)break;u'A7H%v} U;p7y3r
if(nLevel&0x10 || istrin>>t[2]){+hVAbME
nLevel &= 0xF;
if(nLevel==1){t[1]=t[2];csym[1]=0;continue;} G SPth5a0An'W:[ L
if(csym[1]=='*'||csym[1]=='/'){
GetExpValue(t+1, csym[1]);
} z0xsqlnW%?5z
else{
GetExpValue(t, csym[0]); C/I?0v~E7V|
t[1]=t[2];csym[0]=csym[1];csym[1]=0;
}
nLevel = 1;
}$C/}}.EKL {p ~
else istrin.clear();
}y1g,CC.dMiQF&D/H'I
else{nERR = -1; break;}
}
if(csym[1])t[2]=0,nReturn=GetExpValue(t+1, csym[1]);WTiqNhBY
else nReturn=GetExpValue(t, csym[0]);&IAme{;Y1dX N(XW}
return nERR==-1?1:0;&G;X-w-JS6BhM
}}unG;xJgm2v
yq3GYD e?6sS
函数模板使用示例:
在以上那段代码的后面加上以下代码:7{P,yt&Kel4PDa4O5D8k
.H~ytY&U3~*K'Y;g&Gp
程序代码:
#include<strstream>@S;zT+SIk'S#v
#include<iostream>A@]~ v/g
#include<string>
using namespace std;Lp@L\R
int main(void)7MmV7D4YZ%\6I
{
string s1;b'oS Tm
while(cin>>s1)#j6tq0g` ?hk
{
istrstream isin(s1.data());V w\0^a P!V
double d;{[;Bg2pWbGd
if(fy_Exp::GetExpValue(isin, d))R1e-}3A,y){n |
{
cout<<d<<endl;
}o`0O^p
else
{^{jrGP
cout<<"ERROR"<<endl;O+T({(?"F[i-P
}
}
return 0;:D tY D&i
}
Ai*{}wC"s
然后编译执行就可以了(*^_^*)S~#|/RkT#o
其它:TC++上一定编译错误,不保证在VC6上也能通过编译6UZ)E7J2I{u"M"l
建议使用VC7或VC更高版本,或者使用GNU C++编译
页:
[1]