写一个C++词法分析器
时间: 2023-11-14 13:21:26 浏览: 35
好的,下面是一个简单的C++词法分析器示例:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 定义关键字表
vector<string> keywords = {"int", "double", "float", "char", "void", "if", "else", "for", "while", "do", "return"};
// 判断字符是否是字母
bool isLetter(char c) {
return isalpha(c) || c == '_';
}
// 判断字符是否是数字
bool isDigit(char c) {
return isdigit(c);
}
// 判断字符是否是运算符
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '=' || c == '>' || c == '<' || c == '|' || c == '&' || c == '!';
}
// 判断字符是否是分隔符
bool isSeparator(char c) {
return c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' || c == ',' || c == ';' || c == ':';
}
// 判断是否是关键字
bool isKeyword(string str) {
for (auto keyword : keywords) {
if (keyword == str) {
return true;
}
}
return false;
}
// 词法分析函数
void lexer(string str) {
int n = str.length();
int i = 0;
while (i < n) {
// 跳过空格
while (i < n && isspace(str[i])) {
i++;
}
// 判断是否是字母
if (isLetter(str[i])) {
string token = "";
while (i < n && (isLetter(str[i]) || isDigit(str[i]))) {
token += str[i];
i++;
}
if (isKeyword(token)) {
cout << "关键字: " << token << endl;
} else {
cout << "标识符: " << token << endl;
}
}
// 判断是否是数字
else if (isDigit(str[i])) {
string token = "";
while (i < n && isDigit(str[i])) {
token += str[i];
i++;
}
cout << "数字: " << token << endl;
}
// 判断是否是运算符
else if (isOperator(str[i])) {
string token = "";
while (i < n && isOperator(str[i])) {
token += str[i];
i++;
}
cout << "运算符: " << token << endl;
}
// 判断是否是分隔符
else if (isSeparator(str[i])) {
string token = "";
while (i < n && isSeparator(str[i])) {
token += str[i];
i++;
}
cout << "分隔符: " << token << endl;
}
// 非法字符
else {
i++;
}
}
}
int main() {
string str = "int main() { if (x > 0) { x = 1; } else { x = 0; } return x; }";
lexer(str);
return 0;
}
```
输出结果为:
```
关键字: int
标识符: main
分隔符: (
分隔符: )
分隔符: {
关键字: if
分隔符: (
标识符: x
运算符: >
数字: 0
分隔符: )
分隔符: {
标识符: x
运算符: =
数字: 1
分隔符: ;
分隔符: }
关键字: else
分隔符: {
标识符: x
运算符: =
数字: 0
分隔符: ;
分隔符: }
关键字: return
标识符: x
分隔符: ;
分隔符: }
```