词法分析器c语言编写代码
时间: 2024-03-16 17:40:26 浏览: 47
词法分析器是编译器中的一个重要组成部分,用于将源代码分解成一个个的词法单元(token)。下面是一个简单的C语言词法分析器的代码示例:
```c
#include <stdio.h>
#include <ctype.h>
// 定义词法单元类型
typedef enum {
IDENTIFIER, // 标识符
NUMBER, // 数字
OPERATOR, // 运算符
DELIMITER, // 分隔符
KEYWORD // 关键字
} TokenType;
// 定义词法单元结构体
typedef struct {
TokenType type; // 类型
char value[100]; // 值
} Token;
// 词法分析函数
void lex(char *input) {
int i = 0;
while (input[i] != '\0') {
// 跳过空格和换行符
if (isspace(input[i])) {
i++;
continue;
}
// 判断标识符或关键字
if (isalpha(input[i])) {
int j = 0;
while (isalnum(input[i])) {
Token token;
token.type = IDENTIFIER;
token.value[j++] = input[i++];
}
token.value[j] = '\0';
// 判断是否为关键字
if (strcmp(token.value, "if") == 0 || strcmp(token.value, "else") == 0 || strcmp(token.value, "while") == 0) {
token.type = KEYWORD;
}
printf("Token: %s, Type: %d\n", token.value, token.type);
continue;
}
// 判断数字
if (isdigit(input[i])) {
int j = 0;
while (isdigit(input[i])) {
Token token;
token.type = NUMBER;
token.value[j++] = input[i++];
}
token.value[j] = '\0';
printf("Token: %s, Type: %d\n", token.value, token.type);
continue;
}
// 判断运算符
if (input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/') {
Token token;
token.type = OPERATOR;
token.value[0] = input[i++];
token.value[1] = '\0';
printf("Token: %s, Type: %d\n", token.value, token.type);
continue;
}
// 判断分隔符
if (input[i] == ';' || input[i] == ',' || input[i] == '(' || input[i] == ')') {
Token token;
token.type = DELIMITER;
token.value[0] = input[i++];
token.value[1] = '\0';
printf("Token: %s, Type: %d\n", token.value, token.type);
continue;
}
// 未识别的字符
printf("Unrecognized character: %c\n", input[i++]);
}
}
int main() {
char input[100];
printf("请输入C语言源代码:\n");
fgets(input, sizeof(input), stdin);
lex(input);
return 0;
}
```
这段代码实现了一个简单的词法分析器,它可以将输入的C语言源代码分解成不同的词法单元,并打印出它们的类型和值。你可以通过调用`lex`函数来进行词法分析,传入的参数是一个C语言源代码字符串。