一行行的分析处理,把关键字保存,查找,输出,在本题中,关键字少,自定义标示符只有字母开头
注意题意: 1 在运算符号的两侧都是空,我用cin读不会读到空,若读到:= + - * / < !这就是运算符号
2 读到界符直接输出
3 读到字母开头的,先去找到第一个不是字母或数字的符号,没找到的话去判断是不是关键字,不是关键字就是自定义的,
找到的话,就去判断前面的是不是关键字(其实有数字的话就不是关键字了,循环下也行),其实不是字母和数字,就是界符号
#include<stdlib.h> #include<iostream> #include<stdio.h> #include<string> using namespace std; string S[5] ={"keyword","identifier","integer","boundary","operator"}; string T[6] ={"main","if","else","for","while","int"}; void f(string s) { if(s[0] >= '0' && s[0] <= '9') { cout<<"("<<S[2]<<","<<s<<")"<<endl; } else { int bj = 0; for(int i = 0; i < 6; i++) { if(s == T[i]) { bj = 1; cout<<"("<<S[0]<<","<<s<<")"<<endl; break; } } if(bj == 0) { cout<<"("<<S[1]<<","<<s<<")"<<endl; } } } int main() { string s; while(cin>>s) { string sx = ""; int len = s.length(); for(int i = 0; i < len; i++) { if(s[i] == '=' || s[i] == '+' || s[i] == '-'||s[i] == '*'|| s[i] == '/' || s[i] == '<' || s[i] == '>' || s[i] == '!') { if(sx.length()) { f(sx); } sx = ""; if(i+1<len&&s[i+1] == '=') { cout<<"("<<S[4]<<","<<s[i]<<s[i+1]<<")"<<endl; i++; } else { cout<<"("<<S[4]<<","<<s[i]<<")"<<endl; } } else if(s[i] == '(' || s[i] == ')' || s[i] == '{'||s[i] == '}'|| s[i] == ',' || s[i] ==';') { if(sx.length()) { f(sx); } sx = ""; cout<<"("<<S[3]<<","<<s[i]<<")"<<endl; } else { sx = sx+s[i]; } } if(sx.length()) { f(sx); } } return 0; }
PS:原来的代码被卡掉了,这个没有,哈哈,修正版