Md.*_*que 3 c bison lexical-analysis flex-lexer
我正在使用Lexical Analysis.为此,我正在使用Flex并获取以下问题.
int cnt = 0,num_lines=0,num_chars=0; // Problem here.
%%
[" "]+[a-zA-Z0-9]+ {++cnt;}
\n {++num_lines; ++num_chars;}
. {++num_chars;}
%%
int yywrap()
{
return 1;
}
int main()
{ yyin = freopen("in.txt", "r", stdin);
yylex();
printf("%d %d %d\n", cnt, num_lines,num_chars);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后,我使用以下命令,它正常工作并创建lex.yy.c.
Rezwans-iMac:laqb-2 rezwan $ flex work.l
然后,我使用以下命令.
Rezwans-iMac:laqb-2 rezwan $ gcc lex.yy.c -ob
并得到以下error:
work.l: In function ‘yylex’:
work.l:3:4: error: ‘cnt’ undeclared (first use in this function); did you mean int’?
[" "]+[a-zA-Z0-9]+ {++cnt;}
^~~
int
work.l:3:4: note: each undeclared identifier is reported only once for each function it appears in
work.l:4:4: error: ‘num_lines’ undeclared (first use in this function)
\n {++num_lines; ++num_chars;}
^~~~~~~~~
work.l:4:17: error: ‘num_chars’ undeclared (first use in this function); did you mean ‘num_lines’?
\n {++num_lines; ++num_chars;}
^~~~~~~~~
num_lines
work.l: In function ‘main’:
work.l:15:23: error: ‘cnt’ undeclared (first use in this function); did you mean ‘int’?
return 0;
^
int
work.l:15:28: error: ‘num_lines’ undeclared (first use in this function)
return 0;
^
work.l:15:38: error: ‘num_chars’ undeclared (first use in this function); did you mean ‘num_lines’?
return 0;
^
num_lines
Run Code Online (Sandbox Code Playgroud)
error如果我修改这样的work.l文件,我没有达到目标.
int cnt = 0,num_lines=0,num_chars=0; // then work properly above command.
%%
[" "]+[a-zA-Z0-9]+ {++cnt;}
\n {++num_lines; ++num_chars;}
. {++num_chars;}
%%
int yywrap()
{
return 1;
}
int main()
{ yyin = freopen("in.txt", "r", stdin);
yylex();
printf("%d %d %d\n", cnt, num_lines,num_chars);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
也就是说,如果我1 tab在此行之前使用int cnt = 0,num_lines=0,num_chars=0;它,它可以正常工作.
现在我有两个问题:
1 tab这行之前有必要使用int cnt = 0,num_lines=0,num_chars=0;吗?为什么?逻辑解释.
是解决此错误的另一种解决方案吗?
我不太确定选项卡问题,但有一种解释是,如果你没有放置选项卡并在第一部分中写入类似于:
int cnt = 0;
Run Code Online (Sandbox Code Playgroud)
然后请注意,在第一部分中,您还可以编写"快捷方式",例如:
Digit [0-9]
Run Code Online (Sandbox Code Playgroud)
这是一个正则表达式,用于定义数字而不是一直写入[0-9]以表示数字.
因此,int cnt = 0;在不使用tab的情况下在第一列中写入就像定义关键字int(这可能是错误告诉你的原因did you mean int’?).因此,tab是一种区分上述两种情况的方法.
根据flex为了编写c/c ++代码,它需要在里面:
%{ ... c/c++ code... %}所以对于你的例子:Run Code Online (Sandbox Code Playgroud)%{ int cnt = 0,num_lines=0,num_chars=0; %}
所以我最好的方法是在里面写你的c代码%{ %}.
| 归档时间: |
|
| 查看次数: |
1072 次 |
| 最近记录: |