Problem Description 小C语言文法 22. < main关键字>→main
每行单词数不超过10个 Input 输入一个小C语言源程序,源程序长度不超过2000个字符,保证输入合法。 Output 按照源程序中单词出现顺序输出,输出二元组形式的单词串。 (单词种类,单词值) 单词一共5个种类: 关键字:用keyword表示 每种单词值用该单词的符号串表示。 Sample Input main() { int a, b; if(a == 10) { a = b; } } Sample Output (keyword,main) (boundary,() (boundary,)) (boundary,{) (keyword,int) (identifier,a) (boundary,,) (identifier,b) (boundary,;) (keyword,if) (boundary,() (identifier,a) (operator,==) (integer,10) (boundary,)) (boundary,{) (identifier,a) (operator,=) (identifier,b) (boundary,;) (boundary,}) (boundary,}) Hint Source cai++ |
#include <iostream>
#include <string>
using namespace std;
string S[5]= {"keyword","identifier","integer","boundary","operator"};
string T[6]= {"main","if","else","for","while","int"};
void panduan(string s)
{
if(s[0]>='0'&&s[0]<='9') //开头是数字肯定就为数字
{
cout<<"("<<S[2]<<","<<s<<")"<<endl;
}
else
{
int f=1;
for(int i=0; i<6; i++)
{
if(s==T[i])
{
f=0;
cout<<"("<<S[0]<<","<<s<<")"<<endl;
break;
}
}
if(f==1)
{
cout<<"("<<S[1]<<","<<s<<")"<<endl;
}
}
}
int main()
{
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())
{
panduan(temp);
}
temp="";
if(i+1<len&&s[i+1]=='=')
{
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;
}