#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
char KeyWord[21][12]={ "and","begin","const","div","do","else","end", "function","if","integer",
"not","or","procedure","program","read","real","then","type","var","while","write" };
char jiefu[9][2]={",",";","(",")","[","]","{","}","#"};
char calfu[13][3]={ "++","--","+","-","*","/","=","<",">","<>","<=",">=",":="};
ifstream ifile;
int search(char a[],int typeID)
{
int i=0;
switch(typeID)
{
case 1: for(i=0;i<21;i++)
{
if(!strcmp(KeyWord[i],a))
return i;
}
return 21;
case 2: for(i=0;i<9;i++)
{
if(!strcmp(jiefu[i],a))
return i+23;
}
case 3: for(i=0;i<13;i++)
{
if(!strcmp(calfu[i],a))
return i+32;
}
}
return -1;
}
char LetterProcess(char ch)
{
char strarray[20];
int i=-1;
while(isalpha(ch) || isdigit(ch) || ch=='_') //关键字的判断
{
strarray[++i]=ch;
ch=ifile.get();
}
strarray[i+1]='\0';
if(search(strarray,1)!=-1)
cout<<strarray<<"----->"<<search(strarray,1)<<endl;
else
cout<<"输入的"<<strarray<<"是非法字符!"<<endl;
return ch;
}
char digitProcess(char ch)
{
char strarray[20];
int i=-1;
while(isdigit(ch))
{
strarray[++i]=ch;
ch=ifile.get();
if(isalpha(ch) || ch=='_')
{
while(isalpha(ch) || isdigit(ch) || ch=='_')
{
strarray[++i]=ch;
ch=ifile.get();
}
strarray[i+1]='\0';
cout<<strarray<<"----->"<<"词法错误!"<<endl;
return ch;
}
}
strarray[i+1]='\0';
cout<<strarray<<"----->"<<22<<endl;
return ch;
}
char OtherProcess(char ch)
{
char strarray[20];
int i=-1;
if(ch==' ')
{
ch=ifile.get();
return ch;
}
while(!isalpha(ch) && !isdigit(ch) && ch!=' ' && (ifile.eof()==0))
{
strarray[++i]=ch;
ch=ifile.get();
}
strarray[i+1]='\0';
if(search(strarray,2)!=-1)
cout<<strarray<<"----->"<<search(strarray,2)<<endl;
else
cout<<strarray<<"----->"<<search(strarray,3)<<endl;
return ch;
}
void main()
{
ifile.open("f:\\mystring.txt");
char ch=ifile.get();
while(!ifile.eof())
{
if(isalpha(ch))
ch=LetterProcess(ch);
else if(isdigit(ch))
ch=digitProcess(ch);
else
ch=OtherProcess(ch);
}
cout<<endl;
}
评论0