資源簡介
設計SAMPLE語言的詞法分析器
檢查要求:
啟動程序后,先輸出作者姓名、班級、學號(可用漢語、英語或拼音);
請求輸入測試程序名,鍵入程序名后自動開始詞法分析并輸出結果;
輸出結果為單詞的二元式序列(樣式見樣板輸出1和2);
要求能發現下列詞法錯誤和指出錯誤性質和位置:
非法字符,即不是SAMPLE字符集的符號;
字符常數缺右邊的單引號(字符常數要求左、右邊用單引號界定,不能跨行);
注釋部分缺右邊的界符*/(注釋要求左右邊分別用/*和*/界定,不能

代碼片段和文件信息
#include
#include
#include
#include
#include
#include
#include?
using?namespace?std;
bool?flag=true;
int?count=1;//record?the?total?number?of?identifier?3637?and?38
int?col=0;//a?sign?of?5?outputs?every?line
char?*identifier[62]={“““and““array““begin““bool““call““case““char““constant““dim““do““else““end““false““for““if“
??????????????????????“input““integer““not““of““or““output““procedure““program““read““real““repeat““set““stop““then““to“
??“true““until““var““while““write““““““““(““)““*““*/““+““““-“
??“.““..““/““/*““:““:=““;““<““<=““<>““=““>““>=““[““]“};
char?word[1000][20];
stack??S;
/**?identify?an?identifier?among?1?to?35*/
int?match(char*?token)
{
for(int?i=1;i<=60;i++)
if(strcmp(tokenidentifier[i])==0)
return?i;
return?0;
}
/**output?the?result?one?by?one*/
void?printToken(int?ichar*?token)
{
if(col%5==0)
{
col=0;
cout< }
col++;
if(i>35?&&?i<39)
{
//note?the?work?in?an?array
int?j=0;
for(j=0;j {
if(strcmp(tokenword[j])==0)
{
cout<<“(“< return?;
}
}
strcpy(word[count]token);
cout<<“(“< }
else
cout<<“(“<
return;
}
void?scanner()
{
//open?the?file
char?fileName[50];
cout<<“請輸入需要檢測文件的路徑:“< cin>>fileName;
fstream?iof;
iof.open(fileNameios::in);
if(!iof)
{
cout<<“Can‘t?find?the?file.“< return?;
}
/*identify*/
int?nullLine=0;
int?line=0;
//Read?a?line?every?time
const?int?LINE_LEN?=?100;?
char?getRead[102];
loop1: iof.getline(getReadLINE_LEN);
line++;
if(!flag)
{
cout<<“\n“<<“Line“< exit(0);
}
if?(getRead[0]==‘\0‘)
{
nullLine++;
if(nullLine==3){
cout< return?;
}
goto?loop1;
}
nullLine=0;
char?token[20];
char??ch;
int?i=0j;
while(i token[0]=‘\0‘;
if(getRead[i]==‘\0‘?||?getRead[i]==‘?‘)
goto?loop1;
ch=getRead[i++];
if(isalpha(ch)){//between?a?and?z?or?between?A?and?Z
?j=1;
?
?token[0]=ch;
?ch=getRead[i++];
?while(isalnum(ch))
?{
?token[j++]=ch;
?ch=getRead[i++];
?}
?token[j]=‘\0‘;
?i--;
?int?m=match(token);
?if?(m)
?{
?printToken(mtoken);
?}
?else?printToken(36token);
?}
else?if(isalnum(ch)??&&?i ?{
?char?token[20];
?int?k=0;
?token[k++]=ch;
?while(isalnum(ch)?&&?i ?{
?ch=getRead[i++];
?token[k++]=ch;
if(isalpha(ch))
?{
?cout<<“\n“<<“Line“< ?exit(0);
?}?
?}
?token[k]=‘\0‘;
?i--;
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件?????????299??2011-10-13?20:11??example1.txt
?????文件?????????125??2011-12-12?21:33??example2.txt
?????文件??????????33??2002-01-07?00:46??example3.txt
?????文件????????6484??2012-01-11?12:17??main.cpp
評論
共有 條評論