C语言编程问题求解答

题目描述
C语言中的合法标识符的定义为:以下划线或字母开头的字母数字串(含下划线)。
完成一个程序实现对输入的n个字符串进行判定,是否为C语言的合法标识符。如果是则输出1,不是则输出0

关于输入
输入的第一行为一个数字,表明有几个输入字串。
后面每一行为一个长度不超过80的字符串。

关于输出
对所有输入的字符串进行判断,是合法标识符则输出1,回车。否则输出0,回车。

例子输入
5
hello_world
my god
i
_stdio
008A
例子输出
1
0
1
1
0


#include <stdio.h>
#include <ctype.h>

#define N 80
char s[N + 1];

int main(void)
{
    int n, ans;
    char *t;

    scanf("%d", &n);
    getchar();
    while (n--)
    {
        gets(s);

        if (!isalpha(s[0]) && s[0] != '_')
        {
            // 非字母或下划线开头则不是标识符
            ans = 0;
        }
        else
        {
            ans = 1;
            t = s + 1;
            while (*t && ans)
            {
                // 字母、下划线或数字,则检查下一个字符
                if (isalpha(*t))
                {
                    t++;
                    continue;
                }
                if (*t == '_')
                {
                    t++;
                    continue;
                }
                if (isdigit(*t))
                {
                    t++;
                    continue;
                }
                // 非字母、下划线或数字则不是标识符
                ans = 0;
                break;
            }
        }

        printf("%d\n", ans);
    }

    return 0;
}