请帮我用c++写一个简单的语言
以下是一个简单的C++程序,用于实现一个简单的语言解释器:
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
// 定义语言关键字
enum class TokenType {
INTEGER,
PLUS,
MINUS,
MUL,
DIV,
END
};
// Token 类,用于表示语言中的一个单词
class Token {
public:
TokenType type;
int value;
Token(TokenType type, int value) : type(type), value(value) {}
};
class Interpreter {
public:
Interpreter(std::string text) : text(text), pos(0), currentToken(nullptr) {}
// 解析输入的表达式
void parse() {
getNextToken();
int result = expression();
std::cout << "解析结果为:" << result << std::endl;
}
private:
std::string text;
int pos;
Token* currentToken;
// 获取下一个 Token
void getNextToken() {
if (pos >= text.size()) {
currentToken = new Token(TokenType::END, 0);
return;
}
char currentChar = text[pos];
if (isdigit(currentChar)) {
std::stringstream ss;
ss << currentChar;
pos++;
while (pos < text.size() && isdigit(text[pos])) {
ss << text[pos];
pos++;
}
int value;
ss >> value;
currentToken = new Token(TokenType::INTEGER, value);
} else if (currentChar == '+') {
currentToken = new Token(TokenType::PLUS, 0);
pos++;
} else if (currentChar == '-') {
currentToken = new Token(TokenType::MINUS, 0);
pos++;
} else if (currentChar == '*') {
currentToken = new Token(TokenType::MUL, 0);
pos++;
} else if (currentChar == '/') {
currentToken = new Token(TokenType::DIV, 0);
pos++;
} else {
std::cout << "无法识别的字符:" << currentChar << std::endl;
exit(1);
}
}
// 检查当前 Token 的类型是否匹配
void eat(TokenType type) {
if (currentToken->type == type) {
getNextToken();
} else {
std::cout << "语法错误" << std::endl;
exit(1);
}
}
// 解析表达式
int expression() {
int result = term();
while (currentToken->type == TokenType::PLUS || currentToken->type == TokenType::MINUS) {
Token* token = currentToken;
if (token->type == TokenType::PLUS) {
eat(TokenType::PLUS);
result += term();
} else if (token->type == TokenType::MINUS) {
eat(TokenType::MINUS);
result -= term();
}
}
return result;
}
// 解析项
int term() {
int result = factor();
while (currentToken->type == TokenType::MUL || currentToken->type == TokenType::DIV) {
Token* token = currentToken;
if (token->type == TokenType::MUL) {
eat(TokenType::MUL);
result *= factor();
} else if (token->type == TokenType::DIV) {
eat(TokenType::DIV);
result /= factor();
}
}
return result;
}
// 解析因子
int factor() {
Token* token = currentToken;
if (token->type == TokenType::INTEGER) {
eat(TokenType::INTEGER);
return token->value;
} else {
std::cout << "语法错误" << std::endl;
exit(1);
}
}
};
int main() {
std::string text;
std::cout << "请输入一个表达式:" << std::endl;
std::getline(std::cin, text);
Interpreter interpreter(text);
interpreter.parse();
return 0;
}
使用该程序,可以输入一个简单的表达式(如 "2 + 3 * 4 - 5"),程序将解析并计算该表达式的结果
原文地址: https://www.cveoy.top/t/topic/h5Su 著作权归作者所有。请勿转载和采集!