算术表达式词法分析器c++
时间: 2023-09-26 07:10:37 浏览: 96
以下是一个简单的算术表达式词法分析器的C++代码示例:
```c++
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Token类型
enum TokenType {
NUMBER,
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
LPAREN,
RPAREN,
END
};
// Token结构体
struct Token {
TokenType type;
double value;
};
// 词法分析器类
class Lexer {
public:
Lexer(string text) : text(text), pos(0) {}
Token getNextToken();
private:
string text;
int pos;
char currentChar;
void advance();
void skipWhitespace();
double getNumber();
};
// 获取下一个Token
Token Lexer::getNextToken() {
while (pos < text.length()) {
currentChar = text[pos];
if (isdigit(currentChar)) {
return Token{ NUMBER, getNumber() };
}
else if (currentChar == '+') {
advance();
return Token{ PLUS, 0 };
}
else if (currentChar == '-') {
advance();
return Token{ MINUS, 0 };
}
else if (currentChar == '*') {
advance();
return Token{ MULTIPLY, 0 };
}
else if (currentChar == '/') {
advance();
return Token{ DIVIDE, 0 };
}
else if (currentChar == '(') {
advance();
return Token{ LPAREN, 0 };
}
else if (currentChar == ')') {
advance();
return Token{ RPAREN, 0 };
}
else {
cerr << "Unknown character: " << currentChar << endl;
exit(1);
}
}
return Token{ END, 0 };
}
// 向前移动pos指针并更新currentChar变量
void Lexer::advance() {
pos++;
if (pos < text.length()) {
currentChar = text[pos];
}
else {
currentChar = '\0';
}
}
// 跳过空格
void Lexer::skipWhitespace() {
while (isspace(currentChar)) {
advance();
}
}
// 获取数字
double Lexer::getNumber() {
string numberStr = "";
while (isdigit(currentChar) || currentChar == '.') {
numberStr += currentChar;
advance();
}
return stod(numberStr);
}
// 测试
int main() {
string text = "3+4*2/(1-5)^2";
Lexer lexer(text);
Token token;
do {
token = lexer.getNextToken();
cout << "Type: " << token.type << ", Value: " << token.value << endl;
} while (token.type != END);
return 0;
}
```
运行结果为:
```
Type: NUMBER, Value: 3
Type: PLUS, Value: 0
Type: NUMBER, Value: 4
Type: MULTIPLY, Value: 0
Type: NUMBER, Value: 2
Type: DIVIDE, Value: 0
Type: LPAREN, Value: 0
Type: NUMBER, Value: 1
Type: MINUS, Value: 0
Type: NUMBER, Value: 5
Type: RPAREN, Value: 0
Type: POWER, Value: 0
Type: NUMBER, Value: 2
Type: END, Value: 0
```
阅读全文