Hi i have a calculator progran which is shown below...i need to make this into a class calculator....i need some ideas to get started....like what should be the member functions, private data members etc.....
#include <iostream>
#include <string>
#include <map>
#include <cctype>
using namespace std;
double number_value;
string string_value;
int no_of_errors;
map<string,double> table;
enum Token_value
{
NAME, NUMBER, END,
PLUS='+', MINUS='-', MUL='*', DIV='/',
PRINT=';', ASSIGN='=', LP='(', RP=')'
};
Token_value cur_tok=PRINT;
double error(const string& s);
Token_value get_token();
double prim(bool get);
double term(bool get);
double expr(bool get);
double expr(bool get)
{
double left=term(get);
for(;;)
switch(cur_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(cur_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 (cur_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(cur_tok!=RP) return error(") expected");
get_token();
return e;
}
default:
return error("primary expected");
}
}
Token_value get_token()
{
char ch=0;
cin>>ch;
switch(ch)
{
case 0:
return cur_tok=END;
case ';':
case '*':
case '/':
case '+':
case '-':
case '(':
case ')':
case '=':
return cur_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 cur_tok=NUMBER;
default:
if(isalpha(ch))
{
cin.putback(ch);
cin>>string_value;
return cur_tok=NAME;
}
error("bad token");
return cur_tok=PRINT;
}
}
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(cur_tok==END)
break;
if(cur_tok==PRINT)
continue;
cout<<expr(false)<<'\n';
}
return no_of_errors;
}