Yacc文件中的字符串库用法

时间:2014-01-25 07:57:46

标签: c yacc lex

我正在尝试使用lax and yacc编写编译器。我首先定义了令牌和语法树,添加了任何相关的操作,但是当我编译它时,我遇到了一些错误。

词法:

%{
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "y.tab.h"
%}

%%

" " {};
"is" {};
[A-Z]+ { return LAYER;}
[0-9]+\.*[0*9]* {return NUMBER;}
"minimum width" {return MIN_WIDTH;}
"maximum width" {return MAX_WIDTH;}
"minimum length" {return MIN_LENGTH;}
"maximum length" {return MAX_LENGTH;}
"minimum space to" {return MIN_SPACE_TO;}
"minimum space" {return MIN_SPACE;}
"with minimum width" {return MIN_W_FILTER;}
"with minimum span" {return MIN_SPAN_FILTER;}

%%

分析器:

%{
#include <stdio.h>
#include <string.h>

extern FILE * file_in;
%}

%start rule

%token <strval> LAYER NUMBER MIN_WIDTH MAX_WIDTH MIN_LENGTH MAX_LENGTH MIN_SPACE MIN_SPACE_TO MIN_W_FILTER MIN_SPAN_FILTER
%%

rule:
    LAYER operation NUMBER {}
    |
    derived_layer operation NUMBER {}
    ;


derived_layer:
    '(' LAYER filter NUMBER ')' {}
    |
    '(' LAYER operation LAYER ')' {}
    ;

operation:
    MIN_WIDTH {}
    |
    MAX_WIDTH {}
    |
    MIN_LENGTH {}
    |
    MAX_LENGTH {}
    |
    MIN_SPACE_TO {}
    ;

filter:
    MIN_W_FILTER {}
    |
    MIN_SPAN_FILTER {}
    ;

%%

int parsefile (const char * FileName)
{

   FILE * fileIn;
   string strFileName = string(FileName);
   fileIn = fopen(strFileName.c_str(),"r");
   if(!fileIn)
   {
      Std::cout << “error while opening file\n”;
   }
   else
   {
      file_in = fileIn;
      flag = cdfparse();

      if(fileIn)
      {
         fclose(fileIn);
      }
   }
}

我收到以下错误:

drc.y: In function ‘parsefile’:
drc.y:53: error: ‘string’ undeclared (first use in this function)
drc.y:53: error: (Each undeclared identifier is reported only once
drc.y:53: error: for each function it appears in.)
drc.y:53: error: expected ‘;’ before ‘strFileName’
drc.y:54: error: ‘strFileName’ undeclared (first use in this function)
drc.y:57: error: expected expression before ‘:’ token
drc.y:57: error: stray ‘\342’ in program
drc.y:57: error: stray ‘\200’ in program
drc.y:57: error: stray ‘\234’ in program
drc.y:57: error: stray ‘\’ in program
drc.y:57: error: stray ‘\342’ in program
drc.y:57: error: stray ‘\200’ in program
drc.y:57: error: stray ‘\235’ in program
drc.y:62: error: ‘flag’ undeclared (first use in this function

我认为错误意味着字符串库未定义,但我已在标题中包含string.h。还不够吗?

2 个答案:

答案 0 :(得分:1)

string.h包含char数组的字符串函数。字符串类型包含在string文件中。使用#include <string>

答案 1 :(得分:1)

您需要包含:

#include <string>
#include <iostream>

parsefile应该返回一些内容,或者应该是void

本声明:

string strFileName = string(FileName);

应该是:

std::string strFileName = FileName;

这句话:

      Std::cout << “error while opening file\n”;

应该是(注意std中的S和引号):

      std::cout << "error while opening file\n";

flag = cdfparse();没有定义或声明,请检查。