C++实现词法分析器

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include

#include

using namespace std;

char inchar[80], token[8];

char character;

int zbbm, p, m = 0, n, row, sum = 0;

char *blz[6] = { "while", "if", "else", "switch", "case" };

void input()

{

for (n = 0; n<8; n++) token[n] = NULL;

character = inchar[p++];

while (character == ' ')

{

character = inchar[p];

p++;

}

if ((character >= 'a'&&character <= 'z') || (character >= 'A'&&character <= 'Z'))

{

m = 0;

while ((character >= '0'&&character <= '9') || (character >= 'a'&&character <= 'z') || (character >= 'A'&&character <= 'Z'))

{

token[m++] = character;

character = inchar[p++];

}

token[m++] = '\0';

p--;

zbbm = 6;

for (n = 0; n<5; n++)

if (strcmp(token, blz[n]) == 0)

{

zbbm = n + 1;

break;

}

}

else if ((character >= '0'&&character <= '9'))

{

{

sum = 0;

while ((character >= '0'&&character <= '9'))

{

sum = sum * 10 + character - '0';

character = inchar[p++];

}

}

p--;

zbbm = 7;

if (sum>32767)

zbbm = -1;

}

else switch (character)

{

case'<':m = 0; token[m++] = character;

character = inchar[p++];

if (character == '=')

{

zbbm = 11;

token[m++] = character;

}

else

{

zbbm = 11;

p--;

}

break;

case'=':m = 0; token[m++] = character;

character = inchar[p++];

if (character == '=')

{

zbbm = 11;

token[m++] = character;

}

else

{

zbbm = 12;

p--;

}

break;

case'+':zbbm = 8; token[0] = character; break;

case'-':zbbm = 9; token[0] = character; break;

case'*':zbbm = 10; token[0] = character; break;

case';':zbbm = 13; token[0] = character; break;

case'#':zbbm = 0; token[0] = character; break;

default: zbbm = -1; break;

}

}

int main()

{

p = 0;

row = 1;

cout << "请输入字符串:" << endl;

do

{

cin.get(character);

inchar[p++] = character;

} while (character != '#');

p = 0;

do

{

input();

switch (zbbm)

{

case 7: cout << "(" << zbbm << "," << sum << ")" << endl; break;

case -1: cout << "Error in row " << row << "!" << endl; break;

case -2: row = row++; break;

default: cout << "(" << zbbm << "," << token << ")" << endl; break;

}

} while (zbbm != 0);

system("pause");

}

相关文档
最新文档