词法分析器 C++代码
时间: 2023-09-26 08:11:35 浏览: 46
以下是一个简单的词法分析器的 C 代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_TOKEN_LEN 100
typedef enum {
INT,
FLOAT,
ID,
ADD_OP,
SUB_OP,
MULT_OP,
DIV_OP,
ASSIGN_OP,
LEFT_PAREN,
RIGHT_PAREN,
SEMICOLON
} token_type;
typedef struct {
token_type type;
char value[MAX_TOKEN_LEN];
} token;
token current_token;
void get_token() {
int i = 0;
char ch = getchar();
while (isspace(ch)) {
ch = getchar();
}
if (isdigit(ch)) {
while (isdigit(ch)) {
current_token.value[i++] = ch;
ch = getchar();
}
if (ch == '.') {
current_token.type = FLOAT;
current_token.value[i++] = ch;
ch = getchar();
while (isdigit(ch)) {
current_token.value[i++] = ch;
ch = getchar();
}
}
else {
current_token.type = INT;
}
ungetc(ch, stdin);
}
else if (isalpha(ch)) {
while (isalnum(ch)) {
current_token.value[i++] = ch;
ch = getchar();
}
ungetc(ch, stdin);
current_token.type = ID;
}
else if (ch == '+') {
current_token.type = ADD_OP;
current_token.value[i++] = ch;
}
else if (ch == '-') {
current_token.type = SUB_OP;
current_token.value[i++] = ch;
}
else if (ch == '*') {
current_token.type = MULT_OP;
current_token.value[i++] = ch;
}
else if (ch == '/') {
current_token.type = DIV_OP;
current_token.value[i++] = ch;
}
else if (ch == '=') {
current_token.type = ASSIGN_OP;
current_token.value[i++] = ch;
}
else if (ch == '(') {
current_token.type = LEFT_PAREN;
current_token.value[i++] = ch;
}
else if (ch == ')') {
current_token.type = RIGHT_PAREN;
current_token.value[i++] = ch;
}
else if (ch == ';') {
current_token.type = SEMICOLON;
current_token.value[i++] = ch;
}
else {
current_token.type = -1;
current_token.value[i++] = ch;
}
current_token.value[i] = '\0';
}
int main() {
while (current_token.type != -1) {
get_token();
printf("Token Type: %d, Value: %s\n", current_token.type, current_token.value);
}
return 0;
}
```
该代码实现了一个简单的词法分析器,可以读取并识别输入的字符串中的基本单词类型,如整数、浮点数、标识符、运算符、括号和分号等,然后输出每个单词的类型和值。