HDU--IMNU集训三:C语言合法标识符 多用库函数 以及 scanf的相关巧用

来源:互联网 发布:射手座男生 知乎 编辑:程序博客网 时间:2024/06/16 00:15

Problem Description

输入一个字符串,判断其是否是C的合法标识符。

Input

输入数据包含多个测试实例,数据的第一行是一个整数n,表示测试实例的个数,然后是n行输入数据,每行是一个长度不超过50的字符串。

Output

对于每组输入数据,输出一行。如果输入数据是C的合法标识符,则输出"yes",否则,输出“no”。

Sample Input

3
12ajf
fi8x_a
ff ai_2

Sample Output

no
yes
no
 
#include<iostream>
#include<stdio.h>
//#include<cstring>
//#include<string>
#include<algorithm>
#include<cmath>
#include<ctype.h>
using namespace std;
int main (void)
{
    int t;   
    scanf("%d%*c",&t);                                                     //输入t后跳过一个字符
    while( t-- )
    {
         int i=0;
         char str[51]; 
         gets(str);
         //getchar();
         if( isalpha(str[0])==0 && str[0]!='_' )
            { cout<<"no"<<endl; continue; }
         for( i=1; i!=strlen(str); i++ )
         {
             if( isalnum( str[i] )==0 && str[i]!='_' )
             {
                 cout<<"no"<<endl;
                 break;
             }
         }
         if( i==strlen(str) )
         cout<<"yes"<<endl;
                
    }
    return 0;
}
 
多用库函数,勤用库函数。

isalpha:

#include <ctype.h>
int isalpha( int ch );

功能:如果参数是字母字符,函数返回非零值,否则返回零值。

isalnum:

#include <ctype.h>
int isalnum( int ch );

功能:如果参数是数字或字母字符,函数返回非零值,否则返回零值。

scanf:

格式字符串的一般形式为:
%  [*]  [输入数据宽度]  [长度]  类型
其中有方括号 [ ] 的项为任选项

“*”符:
用以表示该输入项,读入后不赋予相应的变量,即跳过该输入值。
如:
scanf("%d %*d %d",&a,&b);
当输入为:1 2 3时,把1赋予a,2被跳过,3赋予b。

%*c作用时读取输入流中数字后的一个字符,并丢弃,使得后面的输入函数不能读到那个字符

跳过一个字符
举个例子
#include "stdio.h"
int main(){
int a, b;
scanf("%d%*c%d", &a, &b);
printf("%d %d\n", a, b);
return 0;
}
你输入1n2,那么scanf把1读取赋给变量a,如果跳过一个char(这里是 ‘n’)接着读取2赋给变量b


0 0
原创粉丝点击