点击阅读原题
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <cctype> using namespace std; int iskey(char tmp[]) { if(!strcmp(tmp,"main")||!strcmp(tmp,"else")||!strcmp(tmp,"if")||!strcmp(tmp,"int")||!strcmp(tmp,"for")||!strcmp(tmp,"while")) return 1; else return 0; } bool isword(char ch) { if(isalpha(ch)) return true; else if(isdigit(ch)) return true; else if(ch=='_') return true; else return false; } int main() { char ch,tmp[100]; int i=0; while(~scanf("%c",&ch)){ if(ch==' '||ch=='\n'||ch=='\t') continue; else if(ch=='('||ch==')'||ch==','||ch=='{'||ch=='}'||ch==';'){ printf("(boundary,%c)\n",ch); } else if(isdigit(ch)){ while(isdigit(ch)){ tmp[i++]=ch; scanf("%c",&ch); } tmp[i]='\0'; printf("(integer,%s)\n",tmp); i=0;ungetc(ch,stdin); } else if(isalpha(ch)||ch=='_'){ while(isword(ch)){ tmp[i++]=ch; scanf("%c",&ch); } tmp[i++]='\0'; i=0; if(iskey(tmp)) printf("(keyword,%s)\n",tmp); else printf("(identifier,%s)\n",tmp); ungetc(ch,stdin); } else if(ch=='+'||ch=='='||ch=='-'||ch=='*'||ch=='/'||ch=='<'||ch=='>'||ch=='!') { char c=ch; scanf("%c",&ch); if(ch=='=') printf("(operator,%c%c)\n",c,ch); else{ printf("(operator,%c)\n",c); ungetc(ch,stdin); } } } return 0; }