一个小型词法分析程序用c语言
时间: 2023-12-02 09:03:37 浏览: 43
下面是一个简单的词法分析程序,可以识别标识符、关键字、数字和运算符:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_TOKEN_LEN 100
enum {
TOKEN_KEYWORD,
TOKEN_IDENTIFIER,
TOKEN_NUMBER,
TOKEN_OPERATOR,
TOKEN_UNKNOWN
};
int get_token_type(char *token) {
if (strcmp(token, "if") == 0 || strcmp(token, "else") == 0 || strcmp(token, "while") == 0 || strcmp(token, "for") == 0) {
return TOKEN_KEYWORD;
}
else if (isdigit(token[0])) {
return TOKEN_NUMBER;
}
else if (isalpha(token[0])) {
return TOKEN_IDENTIFIER;
}
else if (strlen(token) == 1 && strchr("+-*/=", token[0]) != NULL) {
return TOKEN_OPERATOR;
}
else {
return TOKEN_UNKNOWN;
}
}
void tokenize(char *input) {
char *token;
char delimiters[] = " \t\n";
token = strtok(input, delimiters);
while (token != NULL) {
int type = get_token_type(token);
switch (type) {
case TOKEN_KEYWORD:
printf("Keyword: %s\n", token);
break;
case TOKEN_IDENTIFIER:
printf("Identifier: %s\n", token);
break;
case TOKEN_NUMBER:
printf("Number: %s\n", token);
break;
case TOKEN_OPERATOR:
printf("Operator: %s\n", token);
break;
case TOKEN_UNKNOWN:
printf("Unknown token: %s\n", token);
break;
}
token = strtok(NULL, delimiters);
}
}
int main() {
char input[1000];
printf("Enter some code:\n");
fgets(input, sizeof(input), stdin);
tokenize(input);
return 0;
}
```
程序使用 `strtok()` 函数将输入字符串划分为单个标记,并使用 `get_token_type()` 函数确定每个标记的类型。最后,程序将每个标记的类型和值输出到控制台上。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)