?? 詞法分析.cpp
字號(hào):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ofstream fout("out.txt");
string SYM[255],ID[255],NUM[255];
int _i=0,_j=0,_k=0;
//pointer of SYM[],ID[]&NUM[].
string Kwords[]={"CONST","VAR","procedure","begin","end","ood","if","then","call","while","do","read","write"};
string BSymbols[]={",","(",")","{","}",";","."};
string CSymbols[]={":=",">=","<=","=","+","-","*","/","#","<",">"};
int min(int a,int b)
{
if (a<=b)return a;else return b;
}
bool isKeyWord(string word)
{
bool flag=false;
for (int i=0;(i<13);i++)
if (word==Kwords[i]) flag=true;
return flag;
}
bool isBorderSymbol(string sym)
{
bool flag=false;
for (int i=0;i<7;i++)
if (sym==BSymbols[i])
{
flag=true;
break;
}
return flag;
}
bool isCalculateSymbol(string sym)
{
bool flag=false;
for (int i=0;i<11;i++)
if (sym==CSymbols[i])
{
flag=true;
break;
}
return flag;
}
bool isDigit(char ch)
{
if(ch>=0x30 && ch<=0x39) return true;
else return false;
}
bool isLetter(char ch)
{
if((ch>=0x61 && ch<=0x7a)||(ch>=0x41&&ch<=0x5a))
return true;
else return false;
}
bool isBSymbol(char ch)
{
return(ch==','||ch=='('||ch==')'||ch=='{'||ch=='}'||ch==';'||ch=='.');
}
bool isCSymbol(char ch)
{
return(ch==':'||ch=='>'||ch=='<'||ch=='='||ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='#');
}
int Typeof(char w)
{
if(isDigit(w)) return 0;
else if(isLetter(w)) return 1;
else if(isBSymbol(w)) return 2;
else if(isCSymbol(w)) return 3;
else return 4;
}
class FileReader
{
private:
ifstream inpfile;
public:
FileReader()
{
inpfile.open("in.txt");
}
~FileReader()
{
inpfile.close();
}
char peekNextChar()
{
if (!inpfile.eof())
{
char p=inpfile.peek();
return p;}
else return 0;
}
char getNextChar()
{
if (!inpfile.eof())
{
char p=inpfile.get();
return p;}
else return 0;
}
bool eof()
{
return inpfile.eof();
}
};
char getch(FileReader* inp)
{
return inp->getNextChar();
}
char peekch(FileReader* inp)
{
return inp->peekNextChar();
}
int main()
{
FileReader f;
char buff[10];
int pos=0;
while(!f.eof())
{
for (int i=0;i<10;i++)buff[i]=0;
pos=0;
buff[pos++]=getch(&f);
while ((Typeof(peekch(&f))==Typeof(buff[0]))||((Typeof(buff[0])==1)&&(Typeof(peekch(&f))==0)))
buff[pos++]=getch(&f);
switch(Typeof(buff[0]))
{
case 0:
fout<<buff<<"\t數(shù)字"<<endl;
break;
case 1:
if (isKeyWord(buff))
{
fout<<buff<<"\t關(guān)鍵字"<<endl;
}
else
{
fout<<buff<<"\t標(biāo)識(shí)符"<<endl;
}
break;
case 2:
if (isBorderSymbol(buff))
{
fout<<buff<<"\t界限符"<<endl;
}
else fout<<buff<<"\t-------------ERROR"<<endl;
break;
case 3:
if (isCalculateSymbol(buff))
{
fout<<buff<<"\t運(yùn)算符"<<endl;
}
else fout<<buff<<"\t-------------ERROR"<<endl;
break;
}
}
return 0;
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -