只要弄懂什么事C语言的合法标识符就比较简单了,
C语言的合法标志符就是一串只能由字母、数字和下划线组成的字符串,
并且要以字母或下划线开头,
只要记住这个就OK了!^ ^
当然也看到了用#include <ctype.h> 的头文件,
然后以isalpha(int ch)函数判断是否为字母字符,
isalnum(int ch)函数判断是否为字母字符或数字,
运用这个方法会更简单,
把两种方法都贴出来了。
下面是自己编的最原始的代码:
#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>
using namespace std;
int islegal(char c)
{
if (c == '_')
return 1;
else if (c >= 'a' && c <= 'z')
return 1;
else if (c >= 'A' && c <= 'Z')
return 1;
else if (c >= '0' && c <= '9')
return 1;
else return 0;
}
int main()
{
char c;
islegal(c);
int n;
while (cin >> n)
{
getchar();
for (int i = 0; i < n; i ++)
{
char str[100];
gets (str);
int len = strlen (str), flag = 1;
for (int j = 0; j < len; j ++)
{
if (!(str[0] >= 'a' && str[0] <= 'z' || str[0] >= 'A' && str[0] <= 'Z' || str[0] == '_'))
{
flag = 0;
break;
}
if (islegal(str[j]) == 0)
{
flag = 0;
break;
}
}
if (flag == 0)
cout << "no" << endl;
else cout << "yes" << endl;
}
}
system ("pause");
return 0;
}
这个第二种比较简单的方法:
#include <ctype.h>
#include <stdio.h>
int main()
{
int n, d, i;
char sym[64];
scanf("%d%*c", &n);
while (n--)
{
gets(sym);
if (sym[0] != '_' && !isalpha(sym[0]))
{
puts("no");
continue;
}
for (d = i = 1 ; sym[i] ; i++)
{
if (!isalnum(sym[i]) && sym[i] != '_')
{
d = 0;
break;
}
}
puts(d ? "yes" : "no");
}
return 0;
}