Reputation: 2625
I have written a simple lex program to perform average of positive numbers , the program is compiling fine but i'm not able to get the expected output.I'm passing the input to the program from a file by giving filename as a commandline argument.The output of the lex program is blank showing no result , i'm a beginner in lex and any help would be appreciated . I have attached the code below. The code is written in redhat linux kernel version 2.4.
%{
#include <stdio.h>
#include <stdlib.h>
%}
%%
[0-9]+ return atoi(yytext);
%%
void main()
{
int val, total = 0, n = 0;
while ( (val = yylex()) > 0 ) {
total += val;
n++;
}
if (n > 0) printf(“ave = %d\n”, total/n);
}
The input file contains numbers 3,6 and 4 and the name of the file is passed as command line argument.
./a.out < input
Upvotes: 1
Views: 549
Reputation: 5307
Your program works for me. I'm a bit suspicious of yywrap
missing, so you probably link with the -lfl
(or something alike) option. This library contains a yywrap
and a main
. Even though I'm not able to reproduce what you see, I'm wary that maybe the main
from libfl
is used. I'm assuming you do get any newlines in the input file on the output. Different linkers have different ways of resolving multiple occurrences of the same symbol.
All in all I think you have to look for the problem in the way your program is built, because the specification seems ok. If you add int yywrap(void) { return 1; }
after your main
, then you can do without libfl
, which is what I would advise any user of lex
and gnu-flex
.
Upvotes: 2