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)
{
string temp="";
for(int i=0; i<s.length(); 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(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;
}