一、词法分析
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char *rwtab[6]={"begin","if","then","while","do","end"};
//syn:单词符号的种别码;
//token:单词符号的字符串
//sum:整数
char token[16];
int sum,syn;
char program[110],ch;//输入程序,单个字符
int p,m;//下标
void scanner(){
//整数,字符(串),其他
for(int i=0; i<16; i++) {
token[i]=NULL;
}
ch=program[p++];
while(ch==' '){
ch=program[p];
p++;
}
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){
m=0;
while((ch>='a'&&ch<'z')||(ch>='A'&&ch<='Z')||(ch>='0'&&ch<='9')){
token[m++]=ch;
ch=program[p++];
}
token[m++]='\0';
p--;
syn=10;
for(int i=0; i<6; i++) {
if(strcmp(token, rwtab[i])==0) {
syn=i+1;
break;
}
}
}
else if(ch>='0' && ch<='9') {
sum=0;
while(ch>='0' && ch<='9') {
sum=sum*10+ch-'0';
ch=program[p++];
}
p--;
syn=11;
if(sum>65536)
syn=-1;
}
else switch(ch) {
case '+':syn=13; token[0]='+'; break;
case '-':syn=14; token[0]='-';break;
case '*':syn=15; token[0]='*'; break;
case '/':syn=16; token[0]='/'; break;
case ':':m=0; token[m++]=ch;
ch=program[p++];
if(ch=='=') {
token[m++]=ch;
syn=18;
}
else {
syn=17;
p--;
}
break;
case '<':m=0; token[m++]=ch;
ch=program[p++];
if(ch=='>') {
token[m++]=ch;
syn=21;
}
else if(ch=='=') {
token[m++]=ch;
syn=22;
}
else {
syn=20;
p--;
}
break;
case '>':m=0; token[m++]=ch;
ch=program[p++];
if(ch=='=') {
token[m++]=ch;
syn=24;
}
else {
syn=23;
p--;
}
break;
case '=':syn=25; token[0]=ch;break;
case ';':syn=26; token[0]=ch;break;
case '(':syn=27; token[0]=ch;break;
case ')':syn=28; token[0]=ch;break;
case '#':syn=0; token[0]=ch;break;
default: syn=-1;break;
}
}
int main()
{
p=0;
printf("please input string:\n");
do{
ch=cin.get();
program[p++]=ch;
}while(ch!='#');
p=0;
do {
scanner();
switch(syn) {
case 11:cout<<"<"<<syn<<","<<sum<<">"<<endl; break;
case -1:cout<<"Error"<<endl; break;
default:cout<<"<"<<syn<<","<<token<<">"<<endl; break;
}
}while(syn!=0);
return 0;
}
二、语法分析