【发布时间】:2017-03-19 00:41:36
【问题描述】:
当一个程序作为文件提供给 lex 时,我已经制作了这个程序来找出 lex 中的关键字和标识符
#include<iostream>
#include<stdio.h>
#include<ctype.h>
#include<string.h>
using namespace std;
void keyw(char *p);
int i=0,id=0,kw=0,num=0,op=0,n=0;
char s[32];
char keys[32][10]={"auto","break","case","char","const","continue","default",
"do","double","else","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while"};
int main()
{
char ch,str[25];
char seps[]=" \t\n,;(){}[]#\"<>";
char oper[]="!%^&*-+=~|.<>/?";
int j;
char fname[50];
FILE *f1;
printf("enter file path\n");
scanf("%s",fname);
f1 = fopen(fname,"r");
if(f1==NULL)
{
printf("file not found");
return 0;
}
while((ch=fgetc(f1))!=EOF)
{
for(j=0;j<=14;j++)
{
if(ch==oper[j])
{
str[i]='\0';
keyw(str);
}
}
for(j=0;j<=14;j++)
{
if(i==-1)
break;
if(ch==seps[j])
{
if(ch=='#')
{
while(ch!='>')
{
ch=fgetc(f1);
}
i=-1;
break;
}
if(ch=='"')
{
do
{
ch=fgetc(f1);
}
while(ch!='"');
i=-1;
break;
}
str[i]='\0';
keyw(str);
}
}
if(i!=-1)
{
str[i]=ch;
i++;
}
else
i=0;
}
return 0;
}
void keyw(char *p)
{
int k,flag=0;
for(k=0;k<=31;k++)
{
if(strcmp(keys[k],p)==0)
{
for(n=0;n<33;n++)
{
if(strcmp(s[n],p)==0)
continue;
else
{
strcpy(s,p);
cout<<s[n]<<"is a keyword";
flag=1;
break;
}
}
}
}
if(flag==0)
{
if(isdigit(p[0]))
num++;
else
{
if(p[0]!='\0')
printf("%s is an identifier\n",p);
}
}
i=-1;
}
// 错误: lex.cpp:在函数‘void keyw(char*)’中: lex.cpp:91:18:错误:从“char”到“const char*”的无效转换 [-fpermissive] if(strcmp(s[n],p)==0) ^ 在 lex.cpp:4:0 包含的文件中: /usr/include/string.h:144:12: 错误:初始化‘int strcmp(const char*, const char*)’的参数 1 [-fpermissive] extern int strcmp (const char *__s1, const char *__s2)
【问题讨论】:
-
s是char[]。s[n]是char。p是char * -
您能否删除所有不相关的代码,以便您的示例仍然重现错误。请提供minimal reproducible example。
-
实际上,如果我将删除代码,那么 lex 将无法工作
-
void keyw(char *p) { int k,flag=0; for(k=0;k
-
那又怎样?现在你有一个编译器错误,所以没有任何效果。更少的代码意味着搜索错误原因的表面积更小。
标签: c++ type-conversion