用C语言编译一个能够分析整数、小数、标识符、主要运算符、主要关键字的词法分析器
时间: 2023-10-01 19:11:51 浏览: 156
词法分析器是编译器的一个重要组成部分,用于将源代码分解成各种标记,例如关键字、标识符、运算符、常数等。下面是一个简单的用C语言编写的词法分析器,可以识别整数、小数、标识符、主要运算符和主要关键字。
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
// 定义关键字
char *keywords[] = {"int", "float", "double", "char", "if", "else", "for", "while"};
// 判断是否为关键字
int is_keyword(char *word) {
int i;
for (i = 0; i < 8; i++) {
if (strcmp(word, keywords[i]) == 0) {
return 1;
}
}
return 0;
}
// 判断是否为数字
int is_digit(char c) {
return (c >= '0' && c <= '9');
}
// 判断是否为字母
int is_letter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
// 词法分析
void lexical_analysis(char *input) {
int i = 0;
int len = strlen(input);
char token[100] = {0};
while (i < len) {
// 跳过空格和换行
if (isspace(input[i])) {
i++;
continue;
}
// 判断是否为数字或小数点
if (is_digit(input[i]) || input[i] == '.') {
int j = 0;
while (is_digit(input[i]) || input[i] == '.') {
token[j++] = input[i++];
}
printf("Number: %s\n", token);
memset(token, 0, sizeof(token));
}
// 判断是否为标识符或关键字
else if (is_letter(input[i])) {
int j = 0;
while (is_letter(input[i]) || is_digit(input[i])) {
token[j++] = input[i++];
}
if (is_keyword(token)) {
printf("Keyword: %s\n", token);
} else {
printf("Identifier: %s\n", token);
}
memset(token, 0, sizeof(token));
}
// 判断是否为运算符
else {
switch (input[i]) {
case '+':
printf("Operator: +\n");
break;
case '-':
printf("Operator: -\n");
break;
case '*':
printf("Operator: *\n");
break;
case '/':
printf("Operator: /\n");
break;
case '=':
printf("Operator: =\n");
break;
case '<':
printf("Operator: <\n");
break;
case '>':
printf("Operator: >\n");
break;
default:
printf("Invalid character: %c\n", input[i]);
break;
}
i++;
}
}
}
int main() {
char input[1000];
printf("Please input code:\n");
fgets(input, 1000, stdin);
lexical_analysis(input);
return 0;
}
```
使用时,输入要分析的代码,程序将输出每个标记的类型。
例如,输入以下代码:
```c
int main() {
int a = 10;
float b = 3.14;
if (a > b) {
printf("a is greater than b\n");
} else {
printf("b is greater than a\n");
}
return 0;
}
```
输出结果为:
```
Keyword: int
Identifier: main
Operator: (
Operator: )
Operator: {
Keyword: int
Identifier: a
Operator: =
Number: 10
Operator: ;
Keyword: float
Identifier: b
Operator: =
Number: 3.14
Operator: ;
Keyword: if
Operator: (
Identifier: a
Operator: >
Identifier: b
Operator: )
Operator: {
Identifier: printf
Operator: (
String: a is greater than b\n
Operator: )
Operator: ;
Operator: }
Keyword: else
Operator: {
Identifier: printf
Operator: (
String: b is greater than a\n
Operator: )
Operator: ;
Operator: }
Keyword: return
Number: 0
Operator: ;
Operator: }
```
阅读全文