詞法分析器(C++/C)
阿新 • • 發佈:2019-01-05
從一個檔案中讀取原始碼,執行後可以直接看到結果,也可在指定檔案中檢視結果。
這個詞法分析器只實現了部分關鍵字、字元等的識別,可在Key[][]陣列自行新增,種別碼的判別與新增用case更加方便,可寫下試試。
#include <iostream> #include <fstream> #include <ctype.h> #include <cstdlib> #include <cstring> using namespace std; char key[6][10]={"begin","if","then","while","do","end"}; ifstream in; ofstream out; void deal(char *ch) { char str[110]; int l,i,j; memset(str,0,sizeof(str)); for(i=0;i<strlen(ch);) { if(ch[i]==' '||ch[i]=='\n'||ch[i]=='\t')//處理空格,製表符,換行符 { i++; } else if(isalpha(ch[i]))//處理遇到的字元 { l=0; str[l++]=ch[i];//暫存字元 i++; while(isdigit(ch[i])|| isalpha(ch[i]))//一直搜尋到最後一個字元或數字 { str[l++]=ch[i]; i++; } str[l]='\0';//封裝為字串 for(j=0;j<6;j++)//檢查是否與給定關鍵字匹配 { if(strcmp(str,key[j])==0)//若匹配則為對應關鍵字 { cout<<"("<<j+1<<","<<str<<")"<<endl;//輸出到dos視窗 out<<"("<<j+1<<","<<str<<")"<<endl;//輸入到檔案 break; } } if(j==6)//若不匹配則為一般字元 { cout<<"(10,"<<str<<")"<<endl; out<<"(10,"<<str<<")"<<endl; } } else if(isdigit(ch[i]))//若遇到數字 { l=0; str[l++]=ch[i];//暫存遇到的數字 i++; while(isdigit(ch[i]))//一直搜尋到數字結尾 { str[l++]=ch[i]; i++; } str[l]='\0'; cout<<"(11,"<<str<<")"<<endl; out<<"(11,"<<str<<")"<<endl; } else//判斷是否為運算子,界符符號 { if(ch[i]=='+') { cout<<"(13,+)"<<endl; out<<"(13,+)"<<endl; } else if(ch[i]=='-') { cout<<"(14,-)"<<endl; out<<"(14,-)"<<endl; } else if(ch[i]=='*') { cout<<"(15,*)"<<endl; out<<"(15,*)"<<endl; } else if(ch[i]=='/') { cout<<"(16,/)"<<endl; out<<"(16,/)"<<endl; } else if(ch[i]==':') { if((i+1)<strlen(ch)&&ch[i+1]=='=') { cout<<"(18,:=)"<<endl; out<<"(18,:=)"<<endl; i++; } else { cout<<"(17,:)"<<endl; out<<"(17,:)"<<endl; } } else if(ch[i]=='<') { if((i+1)<strlen(ch)&&ch[i+1]=='>') { cout<<"(21,<>)"<<endl; out<<"(21,<>)"<<endl; i++; } else if((i+1)<strlen(ch)&&ch[i+1]=='=') { cout<<"(22,<=)"<<endl; out<<"(22,<=)"<<endl; i++; } else { cout<<"(20,<)"<<endl; out<<"(20,<)"<<endl; } } else if(ch[i]=='>') { if((i+1)<strlen(ch)&&ch[i+1]=='=') { cout<<"(24,>=)"<<endl; out<<"(24,>=)"<<endl; i++; } else { cout<<"(23,>)"<<endl; out<<"(23,>)"<<endl; } } else if(ch[i]=='=') { cout<<"(25,=)"<<endl; out<<"(25,=)"<<endl; } else if(ch[i]==';') { cout<<"(26,;)"<<endl; out<<"(26,;)"<<endl; } else if(ch[i]=='(') { cout<<"(27,()"<<endl; out<<"(27,()"<<endl; } else if(ch[i]==')') { cout<<"(28,))"<<endl; out<<"(28,))"<<endl; } else if(ch[i]=='#') { cout<<"(0,#)"<<endl; out<<"(0,#)"<<endl; } else { cout<<"出錯"<<endl; out<<"出錯"<<endl; exit(0); } i++; } } } int main() { char ch[110],s; /*int sum=0; do{ s=cin.get(); ch[sum++]=s; }while(s!='#'); ch[sum]='\0'; deal(ch); */ char in_name[50],out_name[50];//讀入檔案 輸出檔案 cout<<"指定讀入檔名:"<<endl; cin>>in_name; in.open(in_name); if(in.fail()) { cout<<"讀入檔案開啟失敗"<<endl; exit(0); } cout<<"指定輸出檔名:"<<endl; cin>>out_name; out.open(out_name); if(out.fail()) { cout<<"寫入檔案開啟失敗"<<endl; exit(0); } while(in.good()&&!in.eof())//如果檔案正常且沒有到達檔案結束 { memset(ch,0,110); in.getline(ch,110); deal(ch); } system("pause"); return 0; }