编译原理 实验1《词法分析》
程序员文章站
2024-03-12 15:41:56
...
一,实验内容
自定义一种程序设计语言,或者选择已有的一种高级语言,编制它的词法分析程序。词法分析程序的实现可以采用任何一种编程语言和编程工具。
从输入的源程序中,识别出各个具有独立意义的单词,即关键字、标识符、常数、运算符、界符。并依次输出各个单词的内部编码及单词符号自身值。(遇到错误时可显示“Error”,然后跳过错误部分继续显示)
以下面一段程序为例
main()
{
int a,b;
a = 10;
b = a + 20;
}
需要识别的词
1.关键字:if、int、for、while、do、return、break、continue;单词种别码为1。
2.标识符;单词种别码为2。
3.常数为无符号整形数;单词种别码为3。
4.运算符包括:+、-、*、/、=单词种别码为4。
5.分隔符包括:,、;、{、}、(、); 单词种别码为5。
二,实验步骤
1,可用符号表如下:
(1)10个数字0,1,2......9
(2)52个字母a,b,c......z,A,B,C......Z
(3)6个分隔符 ,;{}()
(4)5个运算符 +-*/=
2,各识别规则的DFA为:
3,代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
char line[100];
string result[100];
int i = 0;
while (cin.getline(line, 100))
{
if (strlen(line) == 0)break;
for (int j = 0; j < strlen(line); j++)
{
char c = line[j];
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '=')
{
result[i] = "4 ";
result[i++] += c;
}
else if (c == ',' || c == ';' || c == '{' || c == '}' || c == '(' || c == ')')
{
result[i] = "5 ";
result[i++] += c;
}
else if (c >= '0'&&c <= '9')
{
result[i] = "3 ";
result[i] += c;
while (line[j + 1] >= '0'&&line[j + 1] <= '9')result[i] += line[++j];
i++;
}
else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
{
result[i] = "2 ";
string s = "";
s += c;
while (line[j + 1] >= '0'&&line[j + 1] <= '9' || line[j + 1] >= 'a' && line[j + 1] <= 'z' || line[j + 1] >= 'A' && line[j + 1] <= 'Z')s += line[++j];
if (s == "if" || s == "int" || s == "for" || s == "while" || s == "do" || s == "return" || s == "break" || s == "continue")result[i] = "1 ";
result[i] += s;
i++;
}
}
}
i = 0;
while (result[i] != "")
{
cout << result[i] << endl;
i++;
}
cout << "end";
system("pause>nul");
return 0;
}
4,结果
三,实验小结
关键字和标识符几乎是一样的,在形式上是一样的,只不过关键字是被系统占用了而已。所以这2个是需要放在一起的,分不开。要先判断是不是关键字或者标识符,然后再枚举,看到底是关键字还是标识符。