c语言写一个词法分析器
时间: 2023-10-27 11:05:28 浏览: 42
好的,下面是一个简单的词法分析器的示例代码,它可以识别整数、加号、减号和乘号等基本运算符:
```c
#include <stdio.h>
#include <ctype.h>
typedef enum {
TOKEN_INTEGER,
TOKEN_PLUS,
TOKEN_MINUS,
TOKEN_MULTIPLY,
TOKEN_EOF
} TokenType;
typedef struct {
TokenType type;
int value;
} Token;
Token nextToken() {
Token token;
int c = getchar();
while (isspace(c)) {
c = getchar();
}
if (isdigit(c)) {
token.type = TOKEN_INTEGER;
token.value = 0;
while (isdigit(c)) {
token.value = token.value * 10 + c - '0';
c = getchar();
}
ungetc(c, stdin);
} else if (c == '+') {
token.type = TOKEN_PLUS;
} else if (c == '-') {
token.type = TOKEN_MINUS;
} else if (c == '*') {
token.type = TOKEN_MULTIPLY;
} else if (c == EOF) {
token.type = TOKEN_EOF;
} else {
printf("Unknown token: %c\n", c);
token.type = TOKEN_EOF;
}
return token;
}
int main() {
Token token;
do {
token = nextToken();
switch (token.type) {
case TOKEN_INTEGER:
printf("INTEGER: %d\n", token.value);
break;
case TOKEN_PLUS:
printf("PLUS\n");
break;
case TOKEN_MINUS:
printf("MINUS\n");
break;
case TOKEN_MULTIPLY:
printf("MULTIPLY\n");
break;
case TOKEN_EOF:
printf("EOF\n");
break;
}
} while (token.type != TOKEN_EOF);
return 0;
}
```
在上面的代码中,我们定义了一个 `TokenType` 枚举,表示不同的令牌类型。然后我们定义了一个 `Token` 结构体,包含令牌的类型和值。函数 `nextToken()` 用来读取下一个令牌,它会忽略空格并识别数字和运算符。最后,我们在主函数中循环调用 `nextToken()` 直到遇到文件结尾。