#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
/*
范式如下:
command->expr’\n’
expr->term{’+'term}
term–>factor { ‘*’ factor}
factor–>‘(’ expr ‘)’ number
number–>digit { digit }
digit–>‘0’‘1’‘2’‘3’‘4’‘5’‘6’‘7’‘8’‘9’
*/
char* input;
int cur=0;
int token;// 保存当前输入的字符
void error(void){
printf (“解析错误 % c\n”,token);
exit(1);
}
void getToken(void){
token = input[cur++];
}
void match(char c){
if(token == c){
getToken();
}else error();
}
//digit–>‘0’‘1’‘2’‘3’‘4’‘5’‘6’‘7’‘8’‘9’
int digit(void){
int result;
if(isdigit(token)){
result = token -‘0’;
match(token);
}else{
error();
}
return result;
}
//number–>digit { digit }
int number(void){
int result =digit();
while(isdigit(token)){
result=10*result+digit();
}
return result;
}
//factor–>‘(’ expr ‘)’ number
int factor(void){
int result;
if(token == ‘(’){
match(’(’);
result = expr();
match(’)’);
}else{
result = number();
}
return result;
}
//term–>factor { ‘*’ factor}
int term(void){
//factor
int result = factor();
// { ‘*’ factor}
while(token==’*’){
match(’*’);
result*=factor();
}
return result;
}
//expr->term{’+‘term}
int expr(void){
//term
int result = term();
//{’+‘term}
while(token == ‘+’){
match(’+’);
result += term();
}
return result;
}
//command->expr’\n’
void command(void){
//expr
int result = expr();
//’\n’
if(token != ‘\n’)
printf (“结果是: % d\n”,result);
else error();
}
void parse(void){
getToken();
command();
}
int main(){
input = (char*)malloc(sizeof(char) * 100);
scanf("%s",input);
parse();
return 0;
}