代码如下:
test.l的代码
%{
/* some initial C programs */
#define BEGINSYM 1
#define INTEGER 2
#define IDNAME 3
#define REAL 4
#define SEMICOLONSYM 5
#define ASSIGNSYM 6
#define STRING 7
%}
/* regular definitions */
Digit [0-9]
Letter [a-zA-Z]
IntLit {Digit}+
Id {Letter}({Letter}|{Digit}|_)*
%%
[ \t\n] {/* skip white spaces */}
[Bb][Ee][Gg][Ii][Nn] {return(BEGINSYM);}
{IntLit} {return(INTEGER);}
{Id} {
printf("var has %d characters, ",yyleng);
return(IDNAME);
}
({IntLit}[.]{IntLit})([Ee][+-]?{IntLit})? {return(REAL);}
\"[^\"\n]*\" {stripquotes(); return(STRING);}
";" {return(SEMICOLONSYM);}
":=" {return(ASSIGNSYM);}
%%
/* some final C programs */
stripquotes()
{
/* handling string within a quoted string */
int frompos, topos=0, numquotes = 2;
for(frompos=1; frompos<yyleng; frompos++){
yytext[topos++] = yytext[frompos];
}
yyleng -= numquotes;
yytext[yyleng] = '\0';
}
void main(){
int i;
i = yylex();
while (i>0 && i < 8) {
printf("<%s> is %d\n",yytext,i);
i = yylex();
}
}
代码主要是识别下面文件的token 的值以及对应number,
测试的text如下
begin
123.4 321.4E21
x:=365;
"this is a string"
上面token以及对应的token number有了,但是我要输出当前token所在的文本的行数 请问我要怎么做呢? 谢谢
编译程序原理