[ACM]Identifiers
题目描述
Identifier is an important concept in the C programming language. Identifiers provide names for several language elements, such as functions, variables, labels, etc.
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.
输入
The first line of the input contains one integer, N, indicating the number of strings in the input. N lines follow, each of which contains at least one and no more than 100 characters. (only upper and lower case alphabetic characters,
digits, underscore (" "), hyphen ("-"), period ("."), comma (","), colon (":"), semicolon (";"), exclamation mark ("!"), question mark ("?"), single and double quotation marks, parentheses, white space and square brackets may appear in the character sequences.)
输出
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
解题思路:本题要求是判断输入的字符是否为合法的标示符,首先判断第一个字符是否符合要求,然后后面的字符逐个判断,如果全部都满足则输出'YES‘。本题函数的运用上面出现了一点问题,分别试用了getline(), cin>>,gets(), cin.getline()函数,cin>>是绝对不行的,因为它不能接受空格,遇到空格字符串则结束。,另外三个函数也都遇到了问题,第一个输入无效。解决方法就是将其屏蔽掉,从第二次输入开始执行。
代码:
#include <iostream> #include <string.h> using namespace std; int main() { int m; int i; cin>>m; for(int i=0;i<=m;i++) { char s1[101]; cin.getline(s1,100,'\n');//输入s1,长度100,接受空格,以换行结束 int n=0; if(i!=0){//这个判断很重要 因为函数cin.getline的限制,把第一次输入屏蔽掉,这个要实际运行看看如果不判断会怎么样 if((s1[0]>='a'&&s1[0]<='z')||(s1[0]>='A'&&s1[0]<='Z')||(s1[0]=='_'))//首先判断第一个字符是否符合要求,符合的话再看后面的字符 { for(int j=1;j<strlen(s1);j++)//遍历后面的字符 { if((s1[j]>='a'&&s1[0]<='z')||(s1[j]>='A'&&s1[j]<='Z')||(s1[j]=='_')||(s1[j]>='0'&&s1[j]<='9')) n++;//判断后面的字符是否每一位都符合要求 } if(n==strlen(s1)-1) cout<<"Yes"<<endl;//如果后面的每一位都符合要求,那么If 里面的等式成立,输出“YES” else cout<<"No"<<endl; } else cout<<"No"<<endl; } } return 0; }
或:
#include <iostream> #include <string.h> using namespace std; int main() { int m; int i; cin>>m; for(int i=0;i<=m;i++) { string s1; getline(cin,s1);//输入s1,长度100,接受空格,以换行结束 int n=0; if(i!=0){//这个判断很重要 因为函数cin.getline的限制,把第一次输入屏蔽掉,这个要实际运行看看如果不判断会怎么样 if((s1[0]>='a'&&s1[0]<='z')||(s1[0]>='A'&&s1[0]<='Z')||(s1[0]=='_'))//首先判断第一个字符是否符合要求,符合的话再看后面的字符 { for(int j=1;j<s1.length();j++)//遍历后面的字符 { if((s1[j]>='a'&&s1[0]<='z')||(s1[j]>='A'&&s1[j]<='Z')||(s1[j]=='_')||(s1[j]>='0'&&s1[j]<='9')) n++;//判断后面的字符是否每一位都符合要求 } if(n==s1.length()-1) cout<<"Yes"<<endl;//如果后面的每一位都符合要求,那么If 里面的等式成立,输出“YES” else cout<<"No"<<endl; } else cout<<"No"<<endl; } } return 0; }
运行截图: