2024
判断c语言的字符串是否是合法的变量名
令人遗憾的是 我的for循环竟然多打了一个分号
调试好久才发现
我竟然瞎想是不是gets函数是不是有什么特殊属性 唉 天真
#include <stdio.h>
int main()
{
    int n,i,j;
    char a[51];
    while (scanf("%d%*c",&n))
    {
        for (i = 0;i < n;i++)
        {
            gets(a);
            if ((a[0] >= 'a' && a[0] <= 'z') || (a[0] >= 'A' && a[0] <= 'Z') || (a[0] == '_'))
            {
                for (j = 1; a[j] != '\0'; j++)
                {
                    if ((a[j] >= 'a' && a[j] <= 'z') || (a[j] >= 'A' && a[j] <= 'Z') || (a[j] == '_') || (a[j] >= '0' && a[j] <= '9'))
                    {
                        printf("yes\n");
                        break;
                    }
                    else
                    {
                        printf("no\n");
                        break;
                    }
                }
            }
            else
            {
                printf("no\n");
            }
        }
    }
    return 0;
}
参考答案
				
#include <ctype.h>
#include <stdio.h>
int main(void)
{
    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;
}
    ========================if i have some wrong, please give me a message, thx.========================
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号