?? cf.cpp
字號:
#include<iostream.h>
#include<stdio.h>
#include<string.h>
const int MAX=120;//規定字符串的最大長度不超過120個字符
char strToken[MAX];//存放當前字符串
int str_2B[50];//存放二進制序列
char *Critical_Word[11]={"gegin","do","else","if","procedure","program","then","var","while","for","switch"};
FILE *fp;
int Isletter(char ch)//是否為英文字母
{
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
return 1;
return 0;
}
int Isdigit(char ch)//是否為數字符號
{
if(ch>='0'&&ch<='9')
return 1;
return 0;
}
int Reserve()//是否為保留字
{
int i;
for(i=0;i<11;i++)
if(strcmp(strToken,Critical_Word[i])==0)
return (i+1);
return 0;
}
void DTB()//將十進制數轉化為二進制數
{
long data=0,t=1;
int i,j=0;
for(i=strlen(strToken)-1;i>=0;--i)//將數字變為十進制數
{
data+=(strToken[i]-'0')*t;
t*=10;
}
if(data==0)
cout<<"0";
else{
while(data)
{
str_2B[j++]=data%2;
data/=2;
}
for(i=j-1;i>=0;--i)
cout<<str_2B[i];
}//else
}//DTB()
void analysis()
{
int i,k,code;
char Buffer[MAX],ch;//緩沖區存放文件中每一行的內容,規定每行最多MAX=120個字符
while(!feof(fp))
{
strcpy(Buffer,"");//清空緩沖區
fgets(Buffer,MAX,fp);
i=0;
while(i<MAX&&ch!='\0')
{
ch=Buffer[i];
if(Isletter(ch))
{
k=0;
while((Isletter(ch)||Isdigit(ch))&&i<MAX)//是標識符
{
strToken[k++]=ch;
ch=Buffer[++i];
}
strToken[k]='\0';
--i;//指針回移一位
ch=' ';
cout<<strToken;
code=Reserve();//匹配保留字,并返回其編碼值
if(code==0)
cout<<"<40,_>"<<"\t一般標識符"<<endl;//一般標識符
else
cout<<"<"<<code<<",_>"<<"\t保留字"<<endl;//保留字
strcpy(strToken,"");
}
else if(Isdigit(ch))
{
k=0;
while(Isdigit(ch)&&i<MAX)//是數字串
{
strToken[k++]=ch;
ch=Buffer[++i];
}
strToken[k]='\0';
--i;//指針回移一位
ch=' ';
cout<<strToken;
cout<<"<50,";//常數
DTB();//十進制數轉化為二進制數并輸出
cout<<">"<<"\t常數"<<endl;
strcpy(strToken,"");
}
else if(ch=='<')
{
cout<<ch;
ch=Buffer[++i];
if(ch=='=')//是小于等于號
cout<<ch<<" <21,_>"<<endl;
else//小于號
{cout<<"<20,_>"<<endl;--i;}
}
else if(ch=='>')
{
cout<<ch;
ch=Buffer[++i];
if(ch=='=')//大于等于號
cout<<ch<<" <23,_>"<<endl;
else//大于號
{cout<<"<22,_>"<<endl;--i;}
}
else if(ch==':')
{
cout<<ch;
ch=Buffer[++i];
if(ch=='=')//等號
cout<<ch<<" <29,_>"<<endl;
}
else if(ch=='*')
{
cout<<ch;
ch=Buffer[++i];
if(ch=='*')
cout<<ch<<" <27,_>"<<endl;//表示數的乘方
else
{cout<<"<28,_>"<<endl;--i;}//一般運算乘號
}
else if(ch=='+')
cout<<ch<<" <30,_>"<<endl;
else if(ch=='-')
cout<<ch<<" <31,_>"<<endl;
else if(ch=='(')
cout<<ch<<" <25,_>"<<endl;
else if(ch==')')
cout<<ch<<" <26,_>"<<endl;
else if(ch=='?')
cout<<ch<<" <32,_>"<<endl;
else if(ch==',')
cout<<ch<<" <33,_>"<<endl;
else if(ch==';')
cout<<ch<<" <34,_>"<<endl;
i++;
}//while(i<MAX)
ch=' ';
}//while(!feof(fp))
fclose(fp);
}//analysis()
int main(void)
{
char filename[20];
cout<<"INPUT THE FILE NAME:"<<endl;
cin>>filename;
if((fp=fopen(filename,"r"))==NULL)
{
cerr<<"Can't open the file,or the file is not exist!!!"<<endl;
return 1;
}
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~詞法開始分析~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
analysis();//調用詞法分析器,并輸出各單詞符號
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~詞法分析結束~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
return 0;
}//main
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -