实现一个计算器,包括加减,乘除,括号,错误提示,id等,相当于一个小型的解释器。
其中重要的思想是
- 把字符转换成token
- 递归解析
//编译原理实现计算器
#include<bits/stdc++.h>
using namespace std;
//int factor(const char **) throw();
enum { //枚举:第一个元素=0,第二个就为1,依次类推
TOKEN_UNKNOWN = 0,
TOKEN_DIGITS,
TOKEN_ADD,
TOKEN_SUB,
TOKEN_MUL,
TOKEN_DIV,
TOKEN_MOD,
TOKEN_OPEN,
TOKEN_CLOSE,
TOKEN_SEMI,
TOKEN_EQUA,
TOKEN_ID,
};
struct Token {
int type;
int value;
string id;
};
struct Exp {
char *exps;
Token t;
map<string, int> m; //存参数
} e;
class ed:public exception {
public:
const char* what() const throw() {
return "ERROR_TYPE_EXPECT_DIGIT";
}
};
class ecp:public exception {
public:
const char* what() const throw() {
return "ERROR_TYPE_EXPECT_CLOSE_PARENTHESIS";
}
};
class dbz:public exception {
public:
const char* what() const throw() {
return "ERROR_TYPE_DIVISION_BY_ZERO";
}
};
class rbz:public exception {
public:
const char* what() const throw() {
return "ERROR_TYPE_REMAINDER_BY_ZERO";
}
};
class un:public exception {
public:
const char* what() const throw() {
return "ERROR_TYPE_UNKNOWN";
}
};
/*
本代码的next函数虽然名为next,但是主要功能还是只有判断token,没有地址++
*/
void next(Exp *e) { //一边扫一边解析就可以
while (*(e->exps) == ' ') { //空格则忽略
(e->exps)++;
}
char c = *(e->exps);
if (isdigit(c)) {
e->t.type = TOKEN_DIGITS;
e->t.value = c - '0