识别保留字:if、int、for、while、do、return、break、continue;
单词种别码为1。
其他的都识别为标识符;单词种别码为2。
常数为无符号整形数;单词种别码为3。
运算符包括:+、-、*、/、=、>、<、>=、<=、!= ;
单词种别码为4。
分隔符包括:,、;、{、}、(、); 单词种别码为5
#include<iostream> #include<fstream> #include<string> #include<string.h> using namespace std; int IsAlpha(char c){ if(((c<='z')&&(c>='a'))||((c<='Z')&&(c>='A'))) return 1; else return 0; } int IsNum(char c){ if(c>='0'&&c<='9') return 1; else return 0; } int IsBound(char c){ if(c=='('||c==')'||c==','||c==';'||c=='{'||c=='}'){ return 1; }else return 0; } int IsOper(char c){ if(c=='+'||c=='-'||c=='*'||c=='/'||c=='='||c=='>'||c=='<'||c=='!') return 1; else return 0; } void Scanner(string s){ char p[20]; for(int i=0;i<(s.length());i++) p[i] = s[i]; for(int i=s.length();i<20;i++) p[i] = '\0'; int f,t; f=0;//word[0] t=0;//word[tail] while(t<=s.length()){ if(IsAlpha(p[t])){//首字符是字母 while(IsAlpha(p[t+1])||IsNum(p[t+1])) t++; char word[t-f+1];//分出来的字符串 for(int i=0;i<t-f+1;i++)word[i]=p[f+i]; word[t-f+1]='\0'; string st1 = word;//切分出的字符串 if(st1=="if"||st1=="int"||st1=="for"||st1=="while"||st1=="do"||st1=="return"||st1=="break"||st1=="continue") cout<<"(1,\""<<st1<<"\")"<<endl;//识别保留字 else cout<<"(2,\""<<st1<<"\")"<<endl;//识别标识符 } else//首字符不是字母 if(IsNum(p[t])){ while(IsNum(p[t+1])) t++; char word[t-f+1];//分出来的字符串 for(int i=0;i<t-f+1;i++)word[i]=p[f+i]; word[t-f+1]='\0'; string st1 = word; cout<<"(3,\""<<st1<<"\")"<<endl;//识别为常数 } else{//首字母不是数字也不是字母 if(p[t]==','||p[t]==';'||p[t]=='{'||p[t]=='}'||p[t]=='('||p[t]==')'){ cout<<"(5,\""<<p[t]<<"\")"<<endl;//识别为分隔符 } else{ if(p[t]=='+'||p[t]=='-'||p[t]=='*'||p[t]=='/'||p[t]=='>'||p[t]=='<'||p[t]=='!'){ if(p[t+1]=='='&&(p[t]=='>'||p[t]=='<'||p[t]=='!')){ cout<<"(5,\""<<p[t]<<p[t+1]<<"\")"<<endl; t++; }else cout<<"(5,\""<<p[t]<<"\")"<<endl; } } } f=t+1; t=f; }//end t>s.length() }; int main(){ cout<<"输入文件路径+名字"<<endl; string fn; cin>>fn; ifstream fin(fn); if (fin.is_open()){ cout<<"文件读取成功"<<endl; string line; while (getline(fin,line)){ Scanner(line); } }else cout<<"文件读取失败"<<endl; return 0; }
原文链接: https://www.cnblogs.com/olhhh/p/13211328.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/360728
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!