Input
輸入一個小C語言源程式,源程式長度不超過2000個字符,保證輸入合法,
Output
按照源程式中單詞出現順序輸出,輸出二元組形式的單詞串,
(單詞種類,單詞值)
單詞一共5個種類:
關鍵字:用keyword表示
自定義識別符號:用identifier表示
整數:用integer表示
界符:用boundary表示
運算子:用operator表示
每種單詞值用該單詞的符號串表示,
#include <iostream>
#include <string>
using namespace std;
void judge(string s)
{
if(s[0]>='0'&&s[0]<='9') //開頭是數字肯定就為數字
{
cout<<"(integer,"<<s<<")"<<endl;
}
else if(s=="main"||s=="if"||s=="else"||s=="for"||s=="while"||s=="int")
{
cout<<"(keyword,"<<s<<")"<<endl;
}
else
{
cout<<"(identifier,"<<s<<")"<<endl;
}
}
void lexical_analysis()
{
string s;
while(cin>>s)
{
int len=s.length();
string temp="";
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(temp.length())
{
judge(temp);
}
temp="";
if(i+1<len&&s[i+1]=='=')
{
cout<<"(operator,"<<s[i]<<s[i+1]<<")"<<endl;
i++;
}
else
{
cout<<"(operator,"<<s[i]<<")"<<endl;
}
}
else if(s[i] == '(' || s[i] == ')' || s[i] == '{'||s[i] == '}'
|| s[i] == ',' || s[i] ==';')
{
if(temp.length())
{
judge(temp);
}
temp="";
cout<<"(boundary,"<<s[i]<<")"<<endl;
}
else
{
temp=temp+s[i];
}
}
if(temp.length())
{
judge(temp);
}
}
}
int main()
{
lexical_analysis();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/35834.html
標籤:其他
