Question

In: Computer Science

C++ Question The first phase of compilation is called scanning or lexical analysis. This phase interprets...

C++ Question

The first phase of compilation is called scanning or lexical analysis. This phase interprets the input program as a sequence of characters and produces a sequence of tokens, which will be used by the parser.

Write a C++ program that implements a simple scanner for a source file given as a command-line argument. The format of the tokens is described below. You may assume that the input is syntactically correct. Optionally, your program can build a symbol table (a hash table is a good choice), which contains an entry for each token that was found in the input. When all the input has been read, your program should produce a summary report that includes a list of all the tokens that appeared in the input, the number of times each token appears in the input and the class of each token. Your program should also list how many times tokens of each category appeared in the input.

Sample token format:

        keyword -> if | then | else | begin | end
        identifier -> character | character identifier
        integer -> digit | digit integer
        real -> integer.integer
        special -> ( | ) | [ | ] | + | - | = | , | ;
        digit -> 0|1|2|3|4|5|6|7|8|9
        character -> a|b|c ... |z|A|B|C ... |Z

Solutions

Expert Solution

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<stdio.h>
#include<string>
#include<map>
#include<vector>
#include<fstream>
#include<cstring>
#include<string.h>
#include<functional>

using namespace std;

map<string, int> classes = {{"keyword",0},{"identifier",0},{"digit",0},{"integer",0},{"real",0},{"character",0},{"alpha",0},{"special",0}};
vector<string> ints = {"0","1","2","3","4","5","6","7","8","9"};
vector<string> key_words = {"if","else","then","begin","end"};
vector<string> identi_fiers = {"(",")","[","]","+","=",",","-",":"};
vector<string> specials = {"(",")","[","]","+","=",",","-",":"};
vector<string> alpha_bets = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
vector<std::string>::iterator iters;

bool is_keyword(string ch);
bool is_identifier(char ch);
bool is_integer(char ch);
bool is_digit(string ch);
bool is_real(string ch);
bool is_char(string ch);
bool is_alpha(char ch);
bool is_special(char ch);

int cnt_key = 0,cnt_ident =0,cnt_digit = 0,cnt_int = 0,cnt_alpha = 0,cnt_char = 0,cnt_real =0,cnt_special=0;

bool is_keyword(string ch)
{
   iters = find(key_words.begin(),key_words.end(),ch);
   if(iters != key_words.end()){
       classes["keyword"]++;
       return true;
   }  
   else{
       return false
   }
}


bool is_identifier(string ch)
{
   iters = find(identi_fiers.begin(),identi_fiers.end(),ch);
   if(iters != identi_fiers.end()){
       classes["identifier"]++;
       return true;
   }  
   else{
       return false
   }
}  

bool is_special(string ch)
{
   iters = find(specials.begin(),specials.end(),ch);
   if(iters != specials.end()){
       classes["special"]++;
       return true;
   }  
   else{
       return false
   }
}  


bool is_digit(string ch)
{
   iters = find(ints.begin(),ints.end(),ch);
   if(iters != ints.end()){
       classes["digit"]++;
       classes["integer"]++;
       return true;
   }  
   else{
       return false
   }
}  

bool is_integer(string ch)
{
   char *p;
   strtol(ch.c_str(), &p , 10);
   if(*p == 0){
       classes["digit"]++;
       return true;
   }  
   else{
       return false
   }
}  

bool is_real(string ch)
{
   bool isreal=false;
   if(ch.find(".") != std::string::npos){
       for(int j=0;j<ch.length;j++){
           if(ch[j] != '.'){
               string search;
               search = ch[j];
               iters = find(ints.begin(),ints.end(),search);
               if(iters != ints.end()){
                   isreal = true;
               }
               else{
                   isreal = false;
               }
           }
   else{;}
       }
   }  
   else {;}
       if(isreal == true){
           classes["real"]++;
       return true;}
       else {return false;}
}

bool is_alpha(string ch)
{
   iters = find(alpha.begin(),alpha.end(),ch);
   if(iters != alpha.end()){
       classes["alpha"]++;
       classes["char"]++;
       return true;
   }  
   else{
       return false
   }
}  


bool is_char(string ch)
{
   bool ischar = false;
   for(int i=0;i<ch.length();i++){
       if(isalpha(ch[i])
           ischar = true;
       else
           ischar = false;
   }
   if(ch.length() >1 && ischar ==true)
   {
       classes["char"]++;
   return true;}      
   else{
       return false
   }
}  

int main(int argc, char *argv[])
{
   int token_cnt = 0; //used to count tokens as they are read.
  
   //atleast one commandline argument must be supplied
   if(argc < 2)
   {
       cerr <<"Error: filename argument not given" <<endl;
       exit(1);
   }
  
   ifstream in_File(argv[1], ios::in) //open file for input.
  
   //check for errors in opening the file
   if(!in_File){
       cerr <<"File" <<argv[1] << "counld not be opened" <<endl;
       exit(1);
   }
  
  
   char lines[100]; //char array used to hold lines of text input
   char *ps; //pointer used to tokenize string
  
   while(in_File.getline(lines,100)){ //reads upto 100chars into lies array
       ps = strtok(lines, " ~'!@#$^&*_{}:<>|?"); //assigns tokenpointer to first token in line
       while(ps != NULL){
           if(is_keyword(ch)){
               cnt_key++;
           }
           else if (isIdentifier(ps)) {
               cnt_ident++; }
           else if (is_char(ps)) {
               cnt_char++; }
           else if (is_digit(ps)) {
               cnt_digit++; }
           else if (is_integer(ps)) {
               cnt_int++; }
           else if (is_real(ps)) {
               cn++; }
           else if (is_alpha(ps)) {
               cnt_alpha++; }
           else {;}
           ps = strtok(lines, " ~'!@#$^&*_{}:<>|?"); //assigns tokenpointer to first token in line
       }
   }
  
std::cout << "CLASS" <<"keyword" <<":" <<classes["keyword"] <<"\n";
std::cout << "CLASS" <<"identifier" <<":" <<classes["identifier"] <<"\n";
std::cout << "CLASS" <<"digit" <<":" <<classes["digit"] <<"\n";
std::cout << "CLASS" <<"integer" <<":" <<classes["integer"] <<"\n";
std::cout << "CLASS" <<"character" <<":" <<classes["char"] <<"\n";
std::cout << "CLASS" <<"alphabet" <<":" <<classes["alpha"] <<"\n";
std::cout << "CLASS" <<"real" <<":" <<classes["real"] <<"\n";
  

in_File.close();
return 0;
}  
  

  
  


Related Solutions

C++ Question The first phase of compilation is called scanning or lexical analysis. This phase interprets...
C++ Question The first phase of compilation is called scanning or lexical analysis. This phase interprets the input program as a sequence of characters and produces a sequence of tokens, which will be used by the parser. Write a C++ program that implements a simple scanner for a source file given as a command-line argument. The format of the tokens is described below. You may assume that the input is syntactically correct. Optionally, your program can build a symbol table...
C++ Question The first phase of compilation is called scanning or lexical analysis. This phase interprets...
C++ Question The first phase of compilation is called scanning or lexical analysis. This phase interprets the input program as a sequence of characters and produces a sequence of tokens, which will be used by the parser. Write a C++ program that implements a simple scanner for a source file given as a command-line argument. The format of the tokens is described below. You may assume that the input is syntactically correct. Optionally, your program can build a symbol table...
The objective of this assignment is to gain an understanding of the lexical analysis phase of...
The objective of this assignment is to gain an understanding of the lexical analysis phase of a compiler and the process of constructing a symbol table. Problem: The first phase of compilation is called scanning or lexical analysis. This phase interprets the input program as a sequence of characters and produces a sequence of tokens, which will be used by the parser. Write a program (in C, C++, C#, Java, or Python) that implements a simple scanner for a source...
Question: Analysis and Design Models: What's the Difference? With the analysis phase behind us, reflect on...
Question: Analysis and Design Models: What's the Difference? With the analysis phase behind us, reflect on the models built for the Theater project. How are they different from the models you plan on using during the design phase. Explain the differences in your own words. Next, find an article and/or video to share with the class on the subject.  
QUESTION 2 You are a Chief Technical Officer (CTO) who is now leading the first phase...
QUESTION 2 You are a Chief Technical Officer (CTO) who is now leading the first phase of implementation of ERP SAP system in your company. The ERP SAP system will bring significant changes to the business processes. Eighty percent of the employees of your company are aged between 40 to 60 years old, with an average of ten years working experiences with the company. a) Based on your knowledge gained in this ERP course, how would the employees react to...
Question 63.33 pts What is the first block in a blockchain called? Group of answer choices...
Question 63.33 pts What is the first block in a blockchain called? Group of answer choices Genesis block First block Alpha block Initial block Question 53.33 pts Data is permanently recorded on the Bitcoin network through files called Group of answer choices Blocks Nounce Node Safety file
C++ program homework question 1 1. Create and implement a class called clockType with the following...
C++ program homework question 1 1. Create and implement a class called clockType with the following data and methods (60 Points.): Data: Hours, minutes, seconds Methods: Set and get hours Set and get minutes Set and get seconds printTime(…) to display time in the form of hh:mm:ss default and overloading constructor Overloading Operators: << (extraction) operator to display time in the form of hh:mm:ss >> (insertion) operator to get input for hours, minutes, and seconds operator+=(int x) (increment operator) to...
Hello, this question relates to a class I am taking called introduction to C++. I have...
Hello, this question relates to a class I am taking called introduction to C++. I have no experience writing programs and outside of learning out of a textbook, and studying on my own, have little understanding of logic. I have been assigned a problem that requires me to write a program for a Grocery Bill, where the consumer inputs the price for 5 items, that the program calculates the total with a 6% sales tax. I really am not sure...
hello i have question in c++ language Q1: create a class called RightTriangleShape, and it has...
hello i have question in c++ language Q1: create a class called RightTriangleShape, and it has data member called height which initialized to 3 by the constructor of the class. It has also the following function members: Void setHeight() to read, and set the height. Void getHeight() to print the value of height. void leftBottom_RTraingle(), prints shape a void leftTop_RTraingle(), prints shape b. void RightTop_RTraingle(), prints shape c. void RigtBottom_RTraingle(), prints shape d. The functions from 3 to 6 have...
AM REALLY IN NEED OF THE NARRATIVE ANALYSIS PART Question 1: Your first task is to...
AM REALLY IN NEED OF THE NARRATIVE ANALYSIS PART Question 1: Your first task is to determine whether your firm is in a competitive industry. Based on the following demand function for the firm's product, what would you answer? Q = 50,000 – 25*P Q is the amount produced and P is the price. . Submit your Competitive Industry Report and Calculations to the dropbox below. Be sure to show your calculations in Excel and provide a narrative analysis in...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT