编译原理_词法分析

简单的词法分析问题,实现了识别关键字、标识符、数字、运算符、边界符的功能



//

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 
       
#include
#include
#include
#include
using namespace std;
string temp="";
string s1;
string ss="";
string keyword[]={"cin","cout","main","string","if","else","while","do","int","char","double","bool","float","return","long","case","break","continue",
"auto","for","goto","const","using","namespace","std"};
string bijiao=">=<";
string bj="()[]{},;";
string ys="+-*/%^&!|";
int getword(int j)
{
int biao=0;
for(int u=j;u
{
if(s1[u]==' ')
break;
else if('a'<=s1[u]&&s1[u]<='z'||'A'<=s1[u]&&s1[u]<='Z')
{
temp=temp+s1[u];
//ss=temp;
}
else if('0'<=s1[u]&&s1[u]<='9')
{
cout<<"数字"<<" "<
biao=1;
//ss=ss+s1[u];
break;
}
int biao1=0;//比较符的标记;
for(int k=0;k
{
if(bijiao[k]==s1[u])
biao1=1;
}
if(biao1==1)
{
cout<<"比较符"<<" "<
biao=1;
//ss=ss+s1[u];
break;
}
int biao2=0;//运算符的标记;
for(int k=0;k
{
if(ys[k]==s1[u])
biao2=1;
}
if(biao2==1)
{
cout<<"运算符"<<" "<
biao=1;
//ss=ss+s1[u];
break;
}
int biao3=0;//边界符的标记;
for(int k=0;k
{
if(bj[k]==s1[u])
biao3=1;
}
if(biao3==1)
{
cout<<"边界符"<<" "<
biao=1;
//ss=ss+s1[u];
break;
}

}
return biao;
}

int main()
{
fstream fin1,fin2;
fin1.open("1.txt");
fin2.open("2.txt");
int hang=1;
while(getline(fin1,s1))
{
int l,b;
cout<
hang++;
l=s1.size();
if(l==0) continue;
if(s1[0]=='#') {cout<
for(int j=0;j
{
if(s1[j]==' '||s1[j]=='\n'||s1[j]=='\t')
{
continue;
}
if('a'<=s1[j]&&s1[j]<='z'||'A'<=s1[j]&&s1[j]<='Z')
{
b=getword(j);
if(b==1)
{
cout<<"标记符号:"<<" "<
j=j+temp.size()-1;
temp="";
continue;
}
int biao5=0;
for(int k=0;k<25;k++)
{
if(keyword[k]==temp)
{
cout<<"特殊符号:"<<" "<
j=j+temp.size()-1;//因为要j++;
break;
}
else
{
cout<<"标记符号:"<<" "<
j=j+temp.size()-1;
temp="";
break;
}
}
}

}
//cout<
// ss="";


}
}

你可能感兴趣的:(编译原理)