还有从书上127页后面的19题到23题,都是跟这个程序有关,我基本上都不会做,那位高手曾经看过,或者现在有时间能看看这本书,给我点提示,好吗?谢谢:)
不是我想偷懒,是这个程序太大有150行,好,我把它贴出来:)
#include<iostream>
#include<string>
#include<map>
#include<cctype>
using namespace std;
program:
END
expr_list END
expr_list:
expression PRINT
expression PRINT expr_list
expression:
expression + term
expression - term
term
term:
term / primary
term * primary
primary
primary:
NUMBER
NAME
NAME = expression
- primary
(expression)
enum Token_value{
NAME, NUMBER, END,
PLUS='+', MINUS='-', MUL='*',DIV='/',
PRINT=';', ASSIGN='=', LP='(',RP=')'
};
Token_value curr_tok=PRINT;
double term(bool);//expr函数中用到了它
double expr(bool get)//处理加和减
{
double left=term(get);
for(;;)
switch(curr_tok)
{
case PLUS:
left+=term(true);
break;
case MINUS:
left-=term(true);
break;
default:return left;
}
}
double prim(bool);//term函数中用到了它
double error(const string &);//term函数中用到了它
double term (bool get)//处理乘和除
{
double left=prim(get);
for(;;)
switch(curr_tok)
{
case MUL:
left*=prim(true);
break;
case DIV:
if(double d=prim(true))
{
left/=d;
break;
}
return error("divide by 0");
default:
break;
}
}
double number_value;
string string_value;
map<string,double>table;//该符号表是一个map
Token_value get_token();//prim函数中用到了它
double prim(bool get)//处理初等项
{
if(get)
get_token();
switch(curr_tok)
{
case NUMBER://浮点常量
{
double v=number_value;
get_token();
return v;
}
case NAME:
{
double &v=table[string_value];
if(get_token()==ASSIGN) v=expr(true);
return v;
}
case MINUS:
return -prim(true);
case LP:
{
double e=expr(true);
if(curr_tok!=RP)
return error(") expected");
get_token();
return e;
}
default:
return error("primary expected");
}
}
Token_value get_token()
{
char ch;
do
{
if(!cin.get(ch))
return curr_tok=END;
}while(ch!='\n'&&isspace(ch));
switch(ch)
{
case';':
case'\n':
return curr_tok=PRINT;
case'*':
case'/':
case'+':
case'-':
case'(':
case')':
case'=':
return curr_tok=Token_value(ch);
case'0':
case'1':
case'2':
case'3':
case'4':
case'5':
case'6':
case'7':
case'8':
case'9':
case'.':
cin.putback(ch);
cin>>number_value;
return curr_tok=NUMBER;
default://NAME,NAME=,或者错误
if(isalpha(ch))
{
cin.putback(ch);
cin>>string_value;
return curr_tok=NAME;
}
error("bad token");
return curr_tok=PRINT;
}
}
int no_of_errors;
double error(const string &s)
{
no_of_errors++;
cerr<<"error:"<<s<<'\n';
return 1;
}
int main()
{
table["pi"]=3.1415926535897932385;
table["e"]=2.7182818284590452354;
while(cin)
{
get_token();
if(curr_tok==END)
break;
if(curr_tok==PRINT)
continue;
cout<<expr(false)<<'\n';
}
return no_of_errors;
}
各位高手拜托 了:)