实验目的:通过设计、编制和调试一个具体的词法分析程序,加深对词法分析的理解。
实验要求:
1. 编制一个具有以下功能的词法分析程序:
a. 输入为字符串(或待进行词法分析的源程序),输出为单词串,即由(单词,类别)所组成的二元组序列;
b. 具有一定的错误检查能力,能够发现并提示不能作为单词的字符串。
2. 提交设计报告,内容包括:
- 实验目的
- 实验要求
- 算法描述
- 程序结构
- 主要变量说明
- 程序清单
- 调试情况
- 设计技巧
- 心得体会
实验一:词法分析程序
设计、编制和调试一个具体的词法分析程序,加深对词法分析的理解。
实验要求:
1. 通过对PL/0词法分析程序(GETSYS)的分析,编制一个具有以下功能的词法分析程序:
a. 输入为字符串(或待进行词法分析的源程序),输出为单词串,即由(单词,类别)所组成的二元组序列;
b. 具有一定的错误检查能力,能够发现并提示不能作为单词的字符串。
程序清单:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_LEN 1000
#define MAX_WORD_LEN 50
char keywords[6][10] = {"if", "else", "while", "for", "int", "void"};
int isKeyword(char *word) {
for (int i = 0; i < 6; i++) {
if (strcmp(keywords[i], word) == 0) {
return 1;
}
}
return 0;
}
int main() {
char input[MAX_LEN];
char word[MAX_WORD_LEN];
int wordIndex = 0;
// Get input from user
printf("Enter the input: ");
gets(input);
// Iterate through the input string
for (int i = 0; i < strlen(input); i++) {
if (isalpha(input[i])) { // If the character is alphabet
word[wordIndex++] = input[i]; // Append it to the current word
} else {
if (wordIndex > 0) { // If there is a word in progress
word[wordIndex] = '\0'; // Add null terminator
if (isKeyword(word)) { // Check if it is a keyword
printf("(%s, keyword)\n", word);
} else { // If not a keyword, consider as identifier
printf("(%s, identifier)\n", word);
}
wordIndex = 0; // Reset word index
}
}
}
return 0;
}
```
调试情况:程序能够准确识别关键字和标识符,并输出其对应的类别。
设计技巧:使用循环遍历输入字符串,通过判断字母字符并记录连续的字母字符,判断是否为关键字或标识符。
心得体会:通过本次实验,加深了对词法分析的理解,掌握了基本的词法分析方法和程序设计技巧。