词法分析器的超前搜索c++代码
时间: 2023-10-28 13:06:15 浏览: 45
下面是一个简单的词法分析器的超前搜索C++代码:
```c++
#include <iostream>
#include <string>
using namespace std;
enum TokenType {
INTEGER,
PLUS,
MINUS,
MUL,
DIV,
LPAREN,
RPAREN,
EOF_TYPE
};
class Token {
public:
TokenType type;
string value;
Token(TokenType type, string value) {
this->type = type;
this->value = value;
}
};
class Lexer {
public:
string text;
int pos;
char current_char;
Lexer(string text) {
this->text = text;
this->pos = 0;
this->current_char = this->text[this->pos];
}
void error() {
throw runtime_error("Invalid character");
}
void advance() {
this->pos++;
if (this->pos > this->text.length() - 1) {
this->current_char = '\0';
} else {
this->current_char = this->text[this->pos];
}
}
void skip_whitespace() {
while (this->current_char != '\0' && isspace(this->current_char)) {
this->advance();
}
}
int integer() {
string result = "";
while (this->current_char != '\0' && isdigit(this->current_char)) {
result += this->current_char;
this->advance();
}
return stoi(result);
}
Token get_next_token() {
while (this->current_char != '\0') {
if (isspace(this->current_char)) {
this->skip_whitespace();
continue;
}
if (isdigit(this->current_char)) {
return Token(INTEGER, to_string(this->integer()));
}
if (this->current_char == '+') {
this->advance();
return Token(PLUS, "+");
}
if (this->current_char == '-') {
this->advance();
return Token(MINUS, "-");
}
if (this->current_char == '*') {
this->advance();
return Token(MUL, "*");
}
if (this->current_char == '/') {
this->advance();
return Token(DIV, "/");
}
if (this->current_char == '(') {
this->advance();
return Token(LPAREN, "(");
}
if (this->current_char == ')') {
this->advance();
return Token(RPAREN, ")");
}
this->error();
}
return Token(EOF_TYPE, "");
}
};
int main() {
while (true) {
string text;
cout << "calc> ";
getline(cin, text);
Lexer lexer(text);
Token token = lexer.get_next_token();
while (token.type != EOF_TYPE) {
cout << "(" << token.type << ", " << token.value << ")" << endl;
token = lexer.get_next_token();
}
cout << "(" << token.type << ", " << token.value << ")" << endl;
}
return 0;
}
```
这个代码实现了一个简单的词法分析器,它可以读取用户输入的算术表达式并将其转换为一系列令牌(Token)。在这个代码中,我们使用了一个枚举类型(TokenType)来表示令牌的类型,使用了一个Token类来表示单个令牌,并使用了一个Lexer类来实现超前搜索算法来逐个获取令牌。