Reputation: 2084
/* def*/
%{
#include <stdio.h>
int vowelCount = 0;
int consonantCount = 0;
%}
/*RULES*/
%%
[aeiouAEIOU] {vowelCount = vowelCount + 1;}
[A-Za-z][^aeiouAEIOU] {consonantCount = consonantCount + 1;}
%%
/*fct*/
int main(void)
{
yylex();
printf ("il y a %d voyelles",vowelCount);
printf ("il y a %d consonnes",consonantCount);
return 0;
}
This is my first ever lex program. I want it to count how many vowels and how many consonants are in the source..
I'm having 2 problems:
I don't get the printf
after yylex until after doing Ctrl+C, and stopping execution. so yylex isn't letting any instructions after it, execute unless I quit stop the entire execution
I'm not geting the correct numbers. For example for "good", I got 1 vowel and 1 consonant instead of 2 vowels and 2 consonants.
What do I need to do to fix these problems?
Upvotes: 2
Views: 1993
Reputation: 241691
Your lex rules never return, so the scan will continue until the end of input is reached. If you are providing input from the console, you need to send an end of input by typing Control-D (linux/mac) / Control-Z (windows) at the beginning of a line.
Your first rule matches any vowel. Your second rule matches any letter followed by a non-vowel. So the matches in good
are:
The newline character which presumably follows good
will also be matched by the default rule.
Note that there is a difference between "anything which is not a vowel" and "a consonant". For example, ! is not a vowel.
The lex default rule (which matches exactly one character if nothing else matches the input at that point) prints the character to stdout. That is almost certainly not what you want, so you should add your own fallback rule which does nothing.
Upvotes: 3