#11279: 利用递归渐降解析器(recursive-descent parser)来解题


foundkey (foundkey)

學校 : 不指定學校
編號 : 58659
來源 : [183.206.161.135]
最後登入時間 :
2017-06-18 18:37:32
a017. 五則運算 | From: [114.221.186.120] | 發表日期 : 2016-08-16 12:23

#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;

int evalExpression(stringstream &str, bool &ok);
int evalTerm(stringstream &str, bool &ok);
int evalFactory(stringstream &str, bool &ok);

int main(void)
{
string str;
stringstream strstream;

while(getline(cin, str)){
strstream.str(str);
bool ok = true;
int result = evalExpression(strstream, ok);

if(ok){
cout << result << endl;
}else{
cout << "Error" << endl;
}
strstream.clear();
}

return 0;
}

int evalExpression(stringstream &str, bool &ok)
{
int result = evalTerm(str, ok);
char token = 0;
while(str >> token){
if('+' != token && '-' != token){
str.unget();
return result;
}
int term = evalTerm(str, ok);
if(ok){
if('+' == token){
result += term;
}else{
result -= term;
}
}else{
return 0;
}

}

return result;
}

int evalTerm(stringstream &str, bool &ok)
{
int result = evalFactory(str, ok);
char token = 0;

while(str >> token){
if('*' != token && '/' != token && '%' != token){
str.unget();
return result;
}

int factory = evalFactory(str, ok);
if(ok){
if('*' == token){
result *= factory;
}else if(0 == factory){
ok = false;
return 0;
}else if('/' == token){
result /= factory;
}else{
result %= factory;
}
}
}

return result;
}

int evalFactory(stringstream &str, bool &ok)
{
string token = "";
int result = 0;

str >> token;

if('(' == token[0]){
result = evalExpression(str, ok);
str >> token;
if(')' != token[0]){
ok = false;
return 0;
}else{
return result;
}
}

return atoi(token.c_str());
}

 
ZeroJudge Forum