C++程序设计语言——一个桌面计算器示例
C++程序设计语言一书中第10章 10.2节的桌面计算器示例。
程序代码
#include <ctype.h>
#include <iostream>
#include <istream>
#include <vector>
#include <string>
#include <map>
using std::map;
using std::string;
static int error_cnt = 0;
//Token defination
enum Kind : char
{
name, number, end,
plus='+', minus='-', mutiple='*', divid='/', lp='(', rp=')',
print=';', assign='='
};
struct Token {
Kind kind;
string string_val;
double number_val;
};
extern double expr(bool);
extern double term(bool);
extern double prim(bool);
// this table is for storing value of variables
// key is name of variable
map<string, double> table;
double error(const string& err_info)
{
error_cnt++;
std::cerr << "error : " << err_info << '\n';
return 1;
}
class TokenStream {
public:
TokenStream(std::istream& s) : ip{
&s}, own{
false} {
};
TokenStream(std::istream* p) : ip{
p}, own{
true