用c++编写一个简单的词法分析器,输出每 个单词符号及种别
时间: 2023-12-03 22:44:48 浏览: 121
以下是一个简单的词法分析器示例,可以识别数字、标识符和运算符(加法和减法):
```c++
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
enum Token {
tok_eof = -1,
tok_number = -2,
tok_identifier = -3,
tok_plus = '+',
tok_minus = '-'
};
static string IdentifierStr;
static double NumVal;
static int gettok() {
static int LastChar = ' ';
while (isspace(LastChar)) {
LastChar = getchar();
}
if (isdigit(LastChar)) {
string NumStr;
do {
NumStr += LastChar;
LastChar = getchar();
} while (isdigit(LastChar) || LastChar == '.');
NumVal = stod(NumStr);
return tok_number;
}
if (isalpha(LastChar)) {
IdentifierStr = LastChar;
while (isalnum((LastChar = getchar()))) {
IdentifierStr += LastChar;
}
if (IdentifierStr == "def") {
return tok_def;
}
if (IdentifierStr == "extern") {
return tok_extern;
}
return tok_identifier;
}
if (LastChar == '+' || LastChar == '-') {
int ThisChar = LastChar;
LastChar = getchar();
return ThisChar;
}
if (LastChar == EOF) {
return tok_eof;
}
int ThisChar = LastChar;
LastChar = getchar();
return ThisChar;
}
int main() {
while (true) {
int Token = gettok();
switch (Token) {
case tok_eof:
return 0;
case tok_number:
cout << "Number: " << NumVal << endl;
break;
case tok_identifier:
cout << "Identifier: " << IdentifierStr << endl;
break;
case tok_plus:
cout << "Operator: +" << endl;
break;
case tok_minus:
cout << "Operator: -" << endl;
break;
default:
cout << "Unexpected token: " << (char) Token << endl;
break;
}
}
}
```
这个示例通过不断地调用 `gettok` 函数来获取下一个标记,并将其与已知的标记进行比较。如果是数字,将其解析为浮点数并返回 `tok_number`;如果是字母,将其解析为标识符并返回 `tok_identifier`;如果是加号或减号,直接返回对应的标记。通过使用枚举类型来表示标记种类,可以使代码更加易于阅读和维护。
阅读全文