1
votes

I am writing a YACC program defining the CFG for vowels in the given string, My code attempt is as follows

%{
#include <stdio.h>
%}

%union{
  char c;   
}

%token <c> VOW

%%
cha :   'a' { printf("a\n"); } 
    | 'e' {printf("e\n");}
    | 'i' {printf("i\n");}
    | 'o' {printf("o\n");}
    | 'u' {printf("u\n");}
    ;
%%

int main(void) {return yyparse();}
int yylex(void) {return getchar();}
void yyerror(char *s) {fprintf(stderr, "%s\n",s);}

Is this a correct definition of a CFG for vowels

1
It depends what exactly you mean. You said 'vowels', and this is a CFG for a language where a legal sentence consists of a single vowel, but if I was implementing this I would want a more precise definition. - user207421
I'm trying to parse a string through this and search for the vowels - 0xtvarun
You seem to be misunderstanding what a CFG is -- CFGs match entire strings, not parts of a string, and describe a langauge of strings. Do you want "all strings that contain vowels" or "all strings that contain only vowels"? Both of those are much easier to do with a simple regular expression rather than yacc. - Chris Dodd
You also seem to be using entirely the wrong tool for the job. You could easily accomplish that objective entirely within flex(1), and you can't really do it at all with yacc(1), at least not well, and you don't need most of what yacc(1) can do for you. You're using a hammer to crack a nut. - user207421

1 Answers

1
votes

You don't need a context-free grammar for your problem, only a regular expresion. You're using the wrong tool for the job. It is three lines in flex(1):

%%
[aeiou] printf("%\n", yytext);
.|\n ;