c语言写的一个词法分析程序,识别标识符的,但是好像逻辑有问题,自己不知道怎么改,求大神指点

2025-02-02 20:02:30
推荐回答(2个)
回答1:

#include
#include
#include
#include  //C99支持bool类型
int main(void)
{
    char str[] = "wordptr_239";
    int t;
    int i;
    t = strlen(str);
    bool ok = true;  //添加标识符,默认合法
    for(i = 0; i < t; i++)
    {
        if(!isdigit(str[0]))
        {
            if(str[i]>='a'&&str[i]<='z'||str[i]>='A'&&str[i]<='Z'||str[i]>='0'&&str[i]<='9'||str[i]=='_')
            {
                printf("%c", str[i]);
                while(str[i] == '#')
                {
                    break;
                }
            }
            else
            {
                printf("非法");
                ok = false;
            }
        }
        else
        {
            printf("非法");
            ok = false;
        }
    }
    if(ok) printf("正确");
    return 0;
}

给你优化了以下,

错误原因如下:

printf("%c", str[i]); //字符打印用%c 不是%s

 

回答2:

第一个IF语句那里 把str[0] 改成 str[i]试试

还有 if(str[i]>='a'&&str[i]<='z'||str[i]>='A'&&str[i]<='Z'||str[i]>='0'&&str[i]<='9'||str[i]=='_')
既然当不是数字的时候才进入判断 那在判断里加入数字的判断又有什么用呢?

在输出的时候 %s 应该改成%c吧 你输出的是字符串中的一个