Professional Documents
Culture Documents
Question #1: Write a small lexical analyzer code. which recognizes the following patterns and
returns appropriate tokens.
I. Operators, ++, --, +-, //, and parenthesis (,)
II. Multiline comments
Place screenshot of file which you read for the above code.
FILE:
int main()
{
fstream obj;
obj.open("D://5th//Compiler Construction Lab//QUIZ.txt", ios::in);
char ch;
if (!obj)
{
cerr << "Unable to create file";
throw; //throws exception if file not open
}
else //writing in file
{
while (!obj.eof())
{
obj.read((char*)&ch, sizeof(char));
cout << ch;
}
}
_getch();
}
OUTPUT:
CODE:
#include<fstream>
#include<iostream>
#include<conio.h>
int main()
{
fstream obj;
obj.open("D://5th//Compiler Construction Lab//QUIZ.txt", ios::in);
char ch;
if (!obj)
{
cerr << "Unable to create file";
throw; //throws exception if file not open
}
else
{
obj.read((char*)&ch, sizeof(char));
while (!obj.eof())
{
if (ch == '+')
{
obj.read((char*)&ch, sizeof(char));
if (ch == '+')
cout << "++ (INCREMENT)\n";
}
else if (ch == '-')
{
obj.read((char*)&ch, sizeof(char));
if (ch == '-')
cout << "-- (DECREMENT)\n";
}
else if (ch == '+')
{
obj.read((char*)&ch, sizeof(char));
if (ch == '-')
cout << "+-\n";
}
else if (ch == '/')
{
obj.read((char*)&ch, sizeof(char));
if (ch == '/')
cout << "// (COMMENT)\n";
}
else if (ch == '(')
{
obj.read((char*)&ch, sizeof(char));
if (ch == ')')
cout << "() (Parenthesis)\n";
}
else
{
obj.read((char*)&ch, sizeof(char)); //for next charc. if
not find DOUBLE same chac.
}
}
}
_getch();
}
OUTPUT:
• Multiline comments
CODE:
#include<iostream>
#include<conio.h>
#include<fstream>
int main()
{
fstream obj1;
char ch_file;
if (!obj1)
{
cerr << "--------Unable to open file-----------"; //THROWS THERE IF
FILE NOT OPENS
throw;
}
else
{
obj1.read((char*)&ch_file, sizeof(char));
while (!obj1.eof())
{
if (ch_file == '/')
{
obj1.read((char*)&ch_file, sizeof(char));
while (ch_file != '/')
{
obj1.read((char*)&ch_file, sizeof(char));
}
obj1.read((char*)&ch_file, sizeof(char));
}
cout << ch_file;
obj1.read((char*)&ch_file, sizeof(char));
}
}
_getch();
}
OUTPUT: