此題只要抓住C語言合法標識符的命名規則就可以了(1、首元素只能是下劃線或是字母,2、除首元素外的元素只能是數字、下劃線和字母),先判斷輸入的字符串首元素是否符合規則,接着再判斷其他元素。要注意的是因爲輸入的是字符串,則在判斷元素是否是數字時是與字符數字判斷!!!
代碼:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n,i,len,b;
char a[50];
cin>>n;
getchar();
for(i=0;i<n;i++)
{
cin.getline(a,50,'\n');
len=strlen(a);
if(a[0]=='_' ||(a[0]>='A' && a[0]<='Z') || (a[0]>='a' && a[0]<='z'))
{
for(b=1;b<len;b++)
{
if((a[b]=='_' )||(a[b]>='A' && a[b]<='Z') || (a[b]>='a' && a[b]<='z') ||(a[b]>='0' && a[b]<='9'))
continue;
else
break;
}
if(b==len)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
else
cout<<"no"<<endl;
}
return 0;
}