Flex program to check if it is a well formed parenthesis or not
This flex program is to check if it is a well formed parenthesis or not. In the program below, if for every open bracket, we do not have the corresponding closing bracket then it is not a well formed parenthesis, else it is a well formed parenthesis.
Here we take input from a file, so we need to only type in the filename in the command prompt where the input is stored, for example(filename.txt).
Check the output below to get a clearer picture.
Input File
Store the following in the input file and name it as input_paranthesis(name anything you want)
((a+b*(b+c))
(a*(b+c))
((a/c)*b)+(b-(-c)))
(a+b)-(c*(d-e))
You will get corresponding output as shown in the screenshot below.
Program
%{ /* Checking if it is a well formed paranthesis or not */ #undef yywrap #define yywrap() 1 int flag=0,ln=1; %} %% "(" {flag++; } ")" { flag--; } [\n] { if(flag==0) printf("\n The statemnet at line no = %d has no missing paranthesis\n\n",ln); else printf("\n Error at line no = %d\n",ln); if(flag>0) printf("The statemnet has either extra ( paranthesis or a missing ) paranthesis\n\n"); else if(flag<0) printf("The statemnet has either extra ) paranthesis or a missing ( paranthesis\n\n"); flag=0; ln++; } %% main() { char fname[100]; printf("\nEnter the name of file\n"); scanf("%s",fname); yyin=fopen(fname,"r+"); yylex(); }