简体   繁体   English

Lex程序什么都不做

[英]Lex program doesn't do anything

I am trying to write a program using Lex which recognizes some letters, numbers and do minor things. 我正在尝试使用Lex编写一个程序,该程序可以识别一些字母,数字并做一些小事情。 The problem is that the program does not recognizes anything. 问题在于该程序无法识别任何内容。 In fact, I changed the rules to a simple rule to recognizes everything, but still does nothing. 实际上,我将规则更改为一个简单的规则以识别所有内容,但仍然不执行任何操作。 What's happening? 发生了什么? Maybe it's simple (it must be, there are few lines), but I am new with Lex and I am not able to fix it. 也许很简单(必须有几行),但是我是Lex的新手,所以无法修复它。 Thanks 谢谢

simple.l: simple.l:

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

  int count = 0;


%}


/*Reglas*/
%%
[a-zA-Z_]*[a-zA-Z_0-9]*      { count++; printf("%s ", yytext); }
.*                           { count++; printf("%s ", yytext); }

%%
/*Procedimientos de usuario*/

int main(int argc, char * argv[]) {
  FILE * yyin;
  if(argc == 2) {
    yyin =fopen(argv[1],"rt");
    if(yyin == NULL) {
      printf("File %s can not be opened\n", argv[1]);
      exit(-1);
    }
  } else {
    printf("Error in arguments");
    exit(-1);
  }


  yylex();
  printf("Counter : %d \n", count);


  fclose(yyin);
  return 0;

}

Imput file: example.txt 输入文件:example.txt

CSC104H1
CSC108H1
CSC204H1
CSC258H1

Also, I need to use ctrl+d to finish the program(as I saw in stackoverflow), if not, the program does not finish by itself. 另外,我需要使用ctrl + d来完成程序(如我在stackoverflow中所看到的),否则,程序不会自行完成。

int main(int argc, char * argv[]) {
  FILE * yyin;
  // ...
  yyin = ....
}

Here, yyin is a local variable . 在这里, yyin是一个局部变量 The scanner is using the global variable with the same name, which this declaration is shadowing. 扫描程序正在使用具有相同名称的全局变量,该变量已被遮盖。

Delete the declaration and it will work fine. 删除声明,它将正常工作。

Your first clue is that the scanner is evidently reading from standard input, not from the file you specified, which is why it waits for you to type an end-of-file indicator. 您的第一个线索是扫描程序显然是从标准输入中读取的,而不是从您指定的文件中读取的,这就是为什么它等待您键入文件结尾指示符的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM