C 模拟词法分析

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

#include<iostream.h>

#include<fstream.H>

#include<stdlib.h>

#include<string.h>

bool letter(char);

bool digit(char);

char keyword[7][7]={"begin","end","if","then","else","while","do"};

char character; //字符变量,存放最新读进的源程序字符

char token[50];

bool flags; //字符数组,存放构成单词符号的字符串

bool putchar()

{

cout<<"您是否是把代码文件写入了analyze.dat文件中?[y(Y)/n(N)]..."<<endl;

char get1;

cin>>get1;

if(get1=='Y'||get1=='y')

{

return true;

}

else

{

return false;

}

}

//-----------------------

void getbc()

{

if(character==' '||character==char(10))

{

if(strlen(token)!=0)

{

for(int k=0;k<7;k++)

{

int a;

if(strlen(keyword[k])>strlen(token))

a=strlen(keyword[k]);

else

a=strlen(token);

if (!strncmp(keyword[k],token,a))

{

cout<<"< "<<token<<" , 保留字>"<<endl;

flags=false;

goto Loop;

}

}

if(!strncmp("+",token,1)||!strncmp("-",token,strlen(token)))

{

cout<<"< "<<token<<" , 算术运算符>"<<endl;

flags=false;

goto Loop;

}

else if(!strncmp("<",token,1)||!strncmp("<=",token,strlen(token))||!strncmp("=<",token,strlen(token))||!strncmp("<>",token,strlen(token))||!strncmp("=",token,strlen(token))||!strncmp(">=",token,strlen(token))||!strncmp(">",token,strlen(token)))

{

cout<<"< "<<token<<" , 关系运算符>"<<endl;

flags=false;

goto Loop;

}

else if(!strncmp(":=",token,2))

{

cout<<"< "<<token<<" , 赋值运算符>"<<endl;

flags=false;

goto Loop;

}

else if(!strncmp(":",token,strlen(token)))

{

cout<<"< "<<token<<" , 冒号>"<<endl;

flags=false;

goto Loop;

}

else if(!strncmp(";",token,strlen(token)))

{

cout<<"< "<<token<<" , 分号>"<<endl;

flags=false;

goto Loop;

}

else if (!strncmp(")",token,strlen(token)))

{

cout<<"< "<<token<<" , 右括号>"<<endl;

flags=false;

goto Loop;

}

else if (!strncmp("(",token,strlen(token)))

{

cout<<"< "<<token<<" , 左括号>"<<endl;

flags=false;

goto Loop;

}

else

{

if (flags==true)

{

cout<<"< "<<token<<", 数>"<<endl;

flags=false;

goto Loop;

}else

cout<<"< "<<token<<", 标示符>"<<endl;

flags=false;

goto Loop;

}

Loop: for(int j=strlen(token);j>=0;j--)

token[j]='\0';

}

}

else if(digit(character))

{

token[strlen(token)]=character;

if(strlen(token)==1)

{

flags=true;

}

}

else if(letter(character))

{

token[strlen(token)]=character;

}

else

token[strlen(token)]=character;

}

bool letter(char character1)

{

if(((char(97)<=character1)&&(character1<=char(122)))||((char(65)<=character1)&&(character1<=char(90))))

return true;

else

return false;

}

bool digit(char character1)

{

if((char(48)<=character1)&&(character1<=char(57)))

return true;

else

return false;

}

void main()

{

bool one;

one=putchar();

if(one==false)

{

cout<<"请准备好了代码再运行此文件"<<endl;

}

else

{

fstream infile;

infile.open ("analyze.dat",ios::in);

char ch;

while(infile.get (ch))

{

character=ch;

getbc();

}

int tmp;

cin>>tmp;

}

}

说明:单词间要有空格!

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航