小C语言--词法分析程序

来源:互联网 发布:淘宝香水正品店推荐 编辑:程序博客网 时间:2024/06/05 19:20
#include<cstdio>#include<cstring>#include<string>using namespace std;bool isLitter(char c){    if(c>='A' && c <='Z'||c>='a'&&c<='z')        return true;    return false;}bool isKey(char *c){    if(!strcmp(c,"main")||!strcmp(c,"if")||!strcmp(c,"int")||       !strcmp(c,"char")||!strcmp(c,"string")||!strcmp(c,"else")       ||!strcmp(c,"else if")||!strcmp(c,"for")||!strcmp(c,"while"))        return true;    return false;}void input(){    int i = 0;    char c,tmp[100];    while(~scanf("%c",&c)){        if(c == '\n' ||c == ' '|| c == '\t') continue;        else if(c=='('||c==')'||c=='{'||c=='}'||c==';'||c==',')            printf("(boundary,%c)\n",c);        else if(isdigit(c)){            while(isdigit(c)){                tmp[i++] = c;                scanf("%c",&c);            }            tmp[i] = '\0';i = 0;            printf("(integer,%s)\n",tmp);            ungetc(c,stdin);        }        else if(isLitter(c) || c =='_'){            while(isLitter(c) || c == '_' || isdigit(c)){                tmp[i++] = c;                scanf("%c",&c);            }            tmp[i] = '\0';i = 0;            if(isKey(tmp))                printf("(keyword,%s)\n",tmp);            else                printf("(identifier,%s)\n",tmp);            ungetc(c,stdin);        }        else{            char t = c;            scanf("%c",&c);            if(c == '=')                printf("(operator,%c%c)\n",t,c);            else{                printf("(operator,%c)\n",t);                ungetc(c,stdin);            }        }    }}int main(){    input();    return 0;}

0 0
原创粉丝点击