You are on page 1of 9

2019103038

Murali R
CD
Lab test

1) Read the input stream and recognize the patterns. Pass the patterns
to the parser along with tokens that define the pattern to the
parser. (sample: separate the input stream into the tokens ofWORD,
NUMBER, andPUNCTUATION).Display the character, word andline
count.

Lex program:

%{
#include<stdio.h>
int line_count = 0,char_count = 0,word_count = 0;
%}

%option noyywrap

%%
[a-zA-Z]+ {
printf("%s - WORD\n",yytext);
word_count++;
char_count += yyleng;
}
[0-9]+ {
printf("%s - NUMBER\n",yytext);
char_count += yyleng;
}
[!".] {
printf("%s - PUNCTUATION\n",yytext);
char_count++;
}
\n {
line_count++;
}
.{

}
%%

int main() {
extern FILE *yyin;
yyin = fopen("inp1.txt","r");
yylex();
printf("\nCharacter count - %d\nWord count - %d\nLine count -
%d\n\n",char_count,word_count,line_count);
}

Output:
2) Write a Lex program to perform the following.

a. String acceptsfrom the command line argument, determine


whether it comprises of only lowercase, mixed case or only upper case
characters.

Lex program:

%option noyywrap
%{
#include <stdio.h>
#include <string.h>
%}

%%
[A-Z]+[\n] { printf("CONTAINS ONLY UPPERCASE LETTERS!\n"); }
[a-z]+[\n] { printf("CONTAINS ONLY LOWERCASE LETTERS!\n"); }
[a-zA-Z]+[\n] {printf("CONTAINS BOTH UPPERCASE AND LOWERCASE
LETTERS!\n");}
.{
}
%%

int main(int argc,char *argv[])


{
yylex();
return 0;
}
b. Reversing each line in a text file. Refer the input string given in Q1.

Lex program:

%option noyywrap
%{
#include<stdio.h>
int i;
%}

%%
[\n]+ ;
.* { for (i=yyleng-1; i>=0; i--)
printf("%c", yytext[i]);
printf("\n"); }
%%
int main()
{
extern FILE *yyin;
yyin = fopen("inp2b.txt","r");
yylex();
return 0;
}
3) Convert the nestedif statement to singleif statement.

%option noyywrap
%{
#include <stdio.h>
int i, n = 0, j;
%}

%%

if\(.+\) {
if(n == 0) {
for(i = 0; i < yyleng-1; i++) {
printf("%c", yytext[i]);
}
n++;
}
else {
printf(" && ");
for(i = 3; i < yyleng-1; i++) {
printf("%c", yytext[i]);
}
n++;
}
}

else.if\(.+\) {
n = 1;
printf("\n");
for(i = 0; i < yyleng-1; i++) {
printf("%c", yytext[i]);
}
}

.*; {
printf(")\n");
i = 0;
while(yytext[i] == ' ' && i < yyleng) {
i++;
}

printf("\t");

while(i < yyleng) {


printf("%c", yytext[i]);
i++;
}
}

.|\n

%%

int main() {
FILE* fd = fopen("inp3.txt", "r");
yyout = fopen("out3.txt","w");
yyin = fd;
yylex();
return 0;
}

You might also like