#include<iostream>
#include<fstream>
#include <string>
using namespace std;
char WORD[5][10]={"int","char","float","for","return"};//关键字
char OPRATOR[11]={'+','-','*','/','<','>','=','(',')','{','}'}; //关键字
string Line[100];
int Line_Num=0;
bool isWORD(char chr[])//关键字判定
{
bool flag=false;
for(int i=0;i<5;i++)
{
if(strcmp(WORD[i],chr)==0)
{
flag=true;
break;
}
}
return flag;
}
bool isOPRATOR(char ch)//运算符判定
{
bool flag=false;
for(int i=0;i<11;i++)
{
if(OPRATOR[i]==ch)
{
flag=true;
break;
}
}
return flag;
}
int main()
{
ifstream input("1.txt",ios::in);//源文件
if(!input)
{
cerr<<"open error!"<<endl;
exit(1);
}else{
cout<<"源程序如下:"<<endl;
while(getline(input,Line[Line_Num]))//读取一行
{
cout<<Line[Line_Num]<<endl;
Line_Num++;
}
cout<<endl<<"词法分析结果如下:"<<endl;
}
for(int i=0;i<Line_Num;i++){
for(int j=0;j<Line[i].length(); j++){
while(Line[i][j]==' '){
j++;
}
char ch=Line[i][j];
if(ch>='A' && ch<='z')//如果是字符
{
int k=0;
char A[10];
while(ch>='A' && ch<='z' || ch>='0' && ch<='9')
{
if(k<10)
{
A[k]=ch;
k++;
}
A[k]='\0';
j++;
ch=Line[i][j];
}
if(isWORD(A)==true){
cout<<"关键字"<<A<<endl;
}else{
cout<<"标识符"<<A<<endl;
}
if(k<10 && isOPRATOR(ch)){
cout<<"运算符"<<ch<<endl;
}
}else{
if(ch>='0' && ch<='9')//如果是是数字
{
int k=0;
char NUM[10];
while(ch>='0' && ch<='9')
{
if(k<10)
{
NUM[k]=ch;
k++;
}
if(Line[i][j]==' '){
}
NUM[k]='\0';
j++;
ch=Line[i][j];
}
cout<<"数字串"<<NUM<<endl;
if(k<10 && isOPRATOR(ch)){
cout<<"运算符"<<ch<<endl;
}
}else
{
if(isOPRATOR(ch)){
cout<<"运算符"<<ch<<endl;
}else{
//cout<<"未识别"<<ch<<endl;
}
}
}
}
}
input.close();
return 0;
}
运行结果: