用C语言代码实现词法分析器
时间: 2023-05-13 12:05:17 浏览: 194
好的,以下是一个简单的用C语言实现的词法分析器:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_TOKEN_LEN 100
typedef enum {
INT,
FLOAT,
OPERATOR,
IDENTIFIER,
KEYWORD
} TokenType;
typedef struct {
TokenType type;
char value[MAX_TOKEN_LEN];
} Token;
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int is_keyword(char* str) {
char* keywords[] = {"if", "else", "while", "for", "int", "float", "return"};
int num_keywords = sizeof(keywords) / sizeof(keywords[0]);
for (int i = 0; i < num_keywords; i++) {
if (strcmp(str, keywords[i]) == 0) {
return 1;
}
}
return 0;
}
Token get_next_token(char* input) {
Token token;
int i = 0;
int len = strlen(input);
// Skip whitespace
while (i < len && isspace(input[i])) {
i++;
}
// Check for end of input
if (i == len) {
token.type = -1;
return token;
}
// Check for integer or float
if (isdigit(input[i])) {
int is_float = 0;
while (i < len && (isdigit(input[i]) || input[i] == '.')) {
if (input[i] == '.') {
is_float = 1;
}
token.value[i] = input[i];
i++;
}
token.value[i] = '\0';
if (is_float) {
token.type = FLOAT;
} else {
token.type = INT;
}
return token;
}
// Check for operator
if (is_operator(input[i])) {
token.type = OPERATOR;
token.value[0] = input[i];
token.value[1] = '\0';
return token;
}
// Check for keyword or identifier
if (isalpha(input[i])) {
while (i < len && (isalpha(input[i]) || isdigit(input[i]))) {
token.value[i] = input[i];
i++;
}
token.value[i] = '\0';
if (is_keyword(token.value)) {
token.type = KEYWORD;
} else {
token.type = IDENTIFIER;
}
return token;
}
// Unknown token
token.type = -1;
return token;
}
int main() {
char input[MAX_TOKEN_LEN];
Token token;
printf("Enter input: ");
fgets(input, MAX_TOKEN_LEN, stdin);
while (1) {
token = get_next_token(input);
if (token.type == -1) {
break;
}
printf("Type: %d, Value: %s\n", token.type, token.value);
input += strlen(token.value);
}
return 0;
}
```
这个词法分析器可以识别整数、浮点数、运算符、关键字和标识符。它会读取用户输入的字符串,并逐个返回识别出的 token,直到输入结束。
阅读全文