1 #include<bits/stdc++.h> 2 #include<list> 3 using namespace std; 4 string str; 5 char line; 6 string num; 7 string s; 8 int flag =0; 9 10 string key[]= {"main","if","else","for","while","int"}; 11 12 int main() 13 { 14 while(cin.get(line)) 15 { 16 str+=line; 17 } 18 for(int i=0; i<=str.size(); i++) 19 { 20 //运算符: = + - * / < <= > >= == != 21 //判断加减乘除 22 if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/') 23 cout<<'('<<"operator"<<","<<str[i]<<')'<<endl; 24 //判断比较符 25 if(str[i]=='='||str[i]=='>'||str[i]=='<'||str[i]=='!') 26 { 27 if(str[i+1]=='=') 28 { 29 cout<<'('<<"operator"<<","<<str[i]<<str[i+1]<<')'<<endl; 30 i++; 31 } 32 else 33 cout<<'('<<"operator"<<","<<str[i]<<')'<<endl; 34 } 35 //界符boundary { } ( ) , ; 36 if(str[i]=='{'||str[i]=='}'||str[i]=='('||str[i]==')'||str[i]==','||str[i]==';') 37 { 38 cout<<'('<<"boundary"<<","<<str[i]<<')'<<endl; 39 } 40 //判断整数 41 if(str[i]>='0'&&str[i]<='9') 42 { 43 while(str[i]>='0'&&str[i]<='9') 44 { 45 num+=str[i]; 46 i++; 47 } 48 i--; 49 cout<<'('<<"integer"<<","<<num<<')'<<endl; 50 num=""; 51 } 52 //当以字母开头 53 if((str[i]<='Z'&&str[i]>='A')||(str[i]<='z'&&str[i]>='a')) 54 { 55 while((str[i]<='Z'&&str[i]>='A')||(str[i]<='z'&&str[i]>='a')||(str[i]<='9'&&str[i]>='0')) 56 { 57 s+=str[i]; 58 i++; 59 } 60 for(int j=0; j<=5; j++) 61 { 62 if(key[j]==s)//判断是否是关键字 63 { 64 flag =1; 65 } 66 } 67 if(flag==1) 68 cout<<'('<<"keyword"<<","<<s<<')'<<endl; 69 else if(flag==0) 70 cout<<'('<<"identifier"<<","<<s<<')'<<endl; 71 s=""; 72 i--; 73 flag=0; 74 } 75 } 76 }
//判断比较符
内容来源于网络如有侵权请私信删除
文章来源: 博客园
- 还没有人评论,欢迎说说您的想法!