int factor(const char*&
txt);
int term(const char*&
txt);
int exp(const char*&
txt)
{
int v
= term(txt);
while (*txt)
{
if (
*txt == ‘+‘ )
{
++txt;
int v2
= term(txt);
v += v2;
}
else if (
*txt == ‘-‘ )
{
++txt;
int v2
= term(txt);
v -= v2;
}
else
{
break ;
}
}
return v;
}
int term(const char*&
txt)
{
int v
= factor(txt);
while (*txt)
{
if (
*txt == ‘*‘ )
{
++txt;
int v2
= term(txt);
v *= v2;
}
else
{
break ;
}
}
return v;
}
int factor(const char*&
txt)
{
if (isdigit(*txt))
{
int v
= *txt - ‘0‘ ;
++txt;
return v;
}
else if (*txt
== ‘(‘)
{
++txt;
int v
= exp(txt);
if (*txt
== ‘)‘ )
{
++txt;
return v;
}
else
throw "invalid
expression" ;
}
else
{
throw "invalid
expression" ;
}
}
int calculate(const char*
txt)
{
if (txt
== nullptr )
throw "invalid
expression" ;
int v
= exp(txt);
//
this is necessary, or 3+4)*5 will be a valid expression.
if (*txt)
throw "invalid
expression" ;
return v;
}
/* Driver program to test above function */
int main()
{
cout << calculate( "3" )
<< endl;
cout << calculate( "3*4" )
<< endl;
cout << calculate( "3+4" )
<< endl;
cout << calculate( "3+4*5" )
<< endl;
cout << calculate( "(3+4)*5" )
<< endl;
cout << calculate( "3*4+5" )
<< endl;
try
{
cout << calculate( "(3+4*5" )
<< endl;
}
catch (const char*
e)
{
cout << e << endl;
}
try
{
cout << calculate( "3+4)*5" )
<< endl;
}
catch (const char*
e)
{
cout << e << endl;
}
try
{
cout << calculate( "3*4+" )
<< endl;
}
catch (const char*
e)
{
cout << e << endl;
}
try
{
cout << calculate( "3*4+x" )
<< endl;
}
catch (const char*
e)
{
cout << e << endl;
}
try
{
cout << calculate( "" )
<< endl;
}
catch (const char*
e)
{
cout << e << endl;
}
return 0;
}