heres the code (full)
Code:
// deskcalc.cpp by "B. Stroustrup"
#include <iostream>
#include <cctype>
#include <map>
#include <string>
using namespace std;
double expr(bool);
double number_value ;
string string_value;
double term(bool);
double prim(bool);
map<string,double>table ;
enum Token_value {
NAME , NUMBER , END ,
PLUS = '+' , MINUS = '-', MUL = '*' ,DIV = '/' ,
PRINT = ';' , ASSIGN = '=' ,LP = '(' , RP = ')'
};
Token_value curr_tok = PRINT ;
int no_of_errors;
double error(const string& s)
{
no_of_errors++ ;
cerr<< "error: "<< s << '/n' ;
return 1 ;
}
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 ;
default : // NAME, NAME = , or error
if( isalpha(ch)){
string_value = ch ;
while( cin.get(ch) && isalnum (ch))
string_value.push_back(ch) ;
// ch would be pushed in string_value . isnt it???
cin.putback(ch);
return curr_tok = NAME ;
}
error("bad token");
return curr_tok = PRINT ;
}
}
double expr(bool get) // add and subtract
{
double left = term (get) ;
for(; ;)
switch (curr_tok) {
case PLUS :
left += term(true);
break;
case MINUS:
left -= term(true);
break;
default :
return left ;
}
}
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:
return left;
}
}
double prim(bool get)
{
if(get) get_token();
switch(curr_tok) {
case NUMBER : //floating point constant
{
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: // unary 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");
}
}
int main()
{
table["pi"] = 3.14159 ;
table["e"] = 2.7182 ;
while(cin)
{
get_token();
if(curr_tok == END ) break ;
if(curr_tok == PRINT ) continue ;
cout << expr(false) <<'\n';
}
return no_of_errors ;
}
i tried your way Eibro but it isnt working. ~:- (
is ";"
I think B. stroustrup didnt see his mistakes. Isn't it Eibro?