小C語言--詞法分析程序

#include <iostream>

using namespace std;
string S[5]={"keyword","identifier","integer","boundary","operator"};
string K[6]={"main","if","else","for","while","int"};
void panduan(string s)
{
    int flag=0;
    if(s[0]>='0'&&s[0]<='9')
    {
        cout<<"("<<S[2]<<","<<s<<")"<<endl;
    }
    else
    {
        for(int i=0;i<6;i++)
        {
            if(K[i]==s)
            {
                flag=1;
                cout<<"("<<S[0]<<","<<s<<")"<<endl;
                break;
            }

        }
        if(flag==0)
        {
            cout<<"("<<S[1]<<","<<s<<")"<<endl;
        }
    }
}
int main()
{
    string s;
    while(cin>>s)
    {
        int len=s.length();
        int i;
        string temp="";
        for(i=0;i<len;i++)
        {
            if(s[i]=='='||s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||s[i]=='<'||s[i]=='>'||s[i]=='!')
            {
                if(temp.length())
                {
                    panduan(temp);
                }
                temp="";
                if(i+1<len&&s[i+1]=='='&&s[i]!='+'&&s[i]!='-'&&s[i]!='*'&&s[i]!='/')//這裏隨便寫
                {
                    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(temp.length())
                {
                    panduan(temp);
                }
                temp="";
                cout<<"("<<S[3]<<","<<s[i]<<")"<<endl;
                }
            else
            {
                temp=temp+s[i];
            }

        }
        if(temp.length())
        {
            panduan(temp);     // 沒有界符和運算符的輸出
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章