2016-11-05 170 views
-6

我做了這個程序來找出關鍵字法和標識當一個程序是作爲一個文件萊克斯轉換無效從CHAR爲const char *

#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:error:從'char'無效轉換爲'const char *'[-fpermissive] if(strcmp(s [n],p )== 0) ^ 從lex.cpp包含的文件中:4:0: /usr/include/string.h:144:12:error:初始化int int strcmp的參數1(const char *,const char *)'[-fpermissive] EXTERN INT STRCMP(爲const char * __ S1,爲const char * __ S2)

+0

's'是一個'char []'。 's [n]'是一個'char'。 'p'是一個char *' – Tibrogargan

+2

你能刪除所有不相關的代碼嗎?所以你的例子仍然會重現錯誤。請提供[MCVE]。 –

+0

實際上,如果我將刪除代碼,那麼lex將不起作用 –

回答

1

此行是錯誤的:

keyw(str); 

取而代之的是,你需要:

keyw(&str); 

功能KEYW(字符* p)需要一個指針或地址。

相關問題