An identifier is a sequence of characters. A valid identifier can contain only upper and lower case alphabetic characters, underscore and digits, and must begin with an alphabetic character or an underscore. Given a list of chararcter sequences, write a program to check if they are valid identifiers.
For each of the N lines, output "Yes" (without quote marks) if the character sequence contained in that line make a valid identifier; output "No" (without quote marks) otherwise.
7 ValidIdentifier valid_identifier valid_identifier 0 invalid identifier 1234567 invalid identifier adefhklmruvwxyz12356790 -.,:;!?‘"()[]ABCDGIJLMQRSTVWXYZ
Yes Yes Yes No No No No
解题思路:
判断是否输入的字符串为合法标识符。
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
using namespace std;
string str[1000];
int main()
{
int n;cin>>n;
getchar();//必须得加这个,吸收空格,否则后面用getline会出错
for(int i=1;i<=n;i++)
{
getline(cin,str[i]);
bool ok=1;
int len=str[i].length();
if(!isalpha(str[i][0])&&str[i][0]!=‘_‘)//首字母不是字母也不是下划线
{
cout<<"No"<<endl;
continue;
}
for(int j=0;j<len;j++)
{
if(!isdigit(str[i][j])&&!isalpha(str[i][j])&&str[i][j]!=‘_‘)//不符合要求
{
ok=0;
break;
}
}
if(ok)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}
[2011山东ACM省赛] Identifiers(模拟),布布扣,bubuko.com
原文:http://blog.csdn.net/sr_19930829/article/details/24271939