Question

write a C++ program that reads in a text file and reads each character or lexemes...

write a C++ program that reads in a text file and reads each character or lexemes and states what token it is and writes to another file

for example:

while (fahr < upper) a = 23.00 whileend

Output:

token lexeme

--------------------------------

keyword while

separator (

identifier fahr

operator <

identifier upper

separator )

identifier a

operator =

real 23.00

keyword whileend

the program aslo reads in comments but does not add to the list. characters that are commented out or pseudocode is not counted

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <iostream>
#include <string.h>
using namespace std;

bool isDelimiter(char ch)
{
   if (ch == ' ' || ch == '+' || ch == '-' || ch == '*' ||
       ch == '/' || ch == ',' || ch == ';' || ch == '>' ||
       ch == '<' || ch == '=' || ch == '(' || ch == ')' ||
       ch == '[' || ch == ']' || ch == '{' || ch == '}')
       return (true);
   return (false);
}

// Returns 'true' if the character is an OPERATOR.
bool isOperator(char ch)
{
   if (ch == '+' || ch == '-' || ch == '*' ||
       ch == '/' || ch == '>' || ch == '<' ||
       ch == '=')
       return (true);
   return (false);
}

bool isSeparator(char ch)
{
if(ch=='(' || ch==')')
{
return true;
}
return false;
}


// Returns 'true' if the string is a VALID IDENTIFIER.
bool validIdentifier(char* str)
{
   if (str[0] == '0' || str[0] == '1' || str[0] == '2' ||
       str[0] == '3' || str[0] == '4' || str[0] == '5' ||
       str[0] == '6' || str[0] == '7' || str[0] == '8' ||
       str[0] == '9' || isDelimiter(str[0]) == true)
       return (false);
   return (true);
}

// Returns 'true' if the string is a KEYWORD.
bool isKeyword(char* str)
{
   if (!strcmp(str, "if") || !strcmp(str, "else") ||
       !strcmp(str, "while") || !strcmp(str, "do") ||
       !strcmp(str, "break") ||
       !strcmp(str, "continue") || !strcmp(str, "int")
       || !strcmp(str, "double") || !strcmp(str, "float")
       || !strcmp(str, "return") || !strcmp(str, "char")
       || !strcmp(str, "case") || !strcmp(str, "char")
       || !strcmp(str, "sizeof") || !strcmp(str, "long")
       || !strcmp(str, "short") || !strcmp(str, "typedef")
       || !strcmp(str, "switch") || !strcmp(str, "unsigned")
       || !strcmp(str, "void") || !strcmp(str, "static")
       || !strcmp(str, "struct") || !strcmp(str, "goto"))
       return (true);
   return (false);
}

// Returns 'true' if the string is an INTEGER.
bool isInteger(char* str)
{
   int i, len = strlen(str);

   if (len == 0)
       return (false);
   for (i = 0; i < len; i++) {
       if (str[i] != '0' && str[i] != '1' && str[i] != '2'
           && str[i] != '3' && str[i] != '4' && str[i] != '5'
           && str[i] != '6' && str[i] != '7' && str[i] != '8'
           && str[i] != '9' || (str[i] == '-' && i > 0))
           return (false);
   }
   return (true);
}


// Returns 'true' if the string is a REAL NUMBER.
bool isRealNumber(char* str)
{
   int i, len = strlen(str);
   bool hasDecimal = false;

   if (len == 0)
       return (false);
   for (i = 0; i < len; i++) {
       if (str[i] != '0' && str[i] != '1' && str[i] != '2'
           && str[i] != '3' && str[i] != '4' && str[i] != '5'
           && str[i] != '6' && str[i] != '7' && str[i] != '8'
           && str[i] != '9' && str[i] != '.' ||
           (str[i] == '-' && i > 0))
           return (false);
       if (str[i] == '.')
           hasDecimal = true;
   }
   return (hasDecimal);
}


// Extracts the SUBSTRING.
char* subString(char* str, int left, int right)
{
   int i;
   char* subStr = (char*)malloc(
               sizeof(char) * (right - left + 2));

   for (i = left; i <= right; i++)
       subStr[i - left] = str[i];
   subStr[right - left + 1] = '\0';
   return (subStr);
}

// Parsing the input STRING.
void parse(char* str)
{
   int left = 0, right = 0;
   int len = strlen(str);
   string outputStr = "";

   while (right <= len && left <= right) {
       if (isDelimiter(str[right]) == false)
           right++;

       if (isDelimiter(str[right]) == true && left == right) {
           if (isOperator(str[right]) == true)
           {
               printf("operator %c\n", str[right]);
           }
           else if(isSeparator(str[right])==true){
           printf("separator %c\n", str[right]);
           }

           right++;
           left = right;
       } else if (isDelimiter(str[right]) == true && left != right
               || (right == len && left != right)) {
           char* subStr = subString(str, left, right - 1);

           if (isKeyword(subStr) == true)
               printf("keyword %s\n", subStr);

           else if (isInteger(subStr) == true)
               printf("integer %s\n", subStr);

           else if (isRealNumber(subStr) == true)
               printf("real %s\n", subStr);

           else if (validIdentifier(subStr) == true
                   && isDelimiter(str[right - 1]) == false)
               printf("identifier %s\n", subStr);

           left = right;
       }
   }
   return;
}

int main()
{

  
  
  
   ifstream inFile;
char str[100] = "while (fahr < upper) a = 23.00 whileend";
//To read the data from the file uncomment the below code and add inputFile.txt in working directory.
// inFile.open("inputFile.txt");
// if (!inFile) {
// cout << "Unable to open file";
// exit(1); // terminate with error
// }
  
// while (inFile >> x) {
// str = str + x;
// }
  
   parse(str);

   return (0);
}

Output:

keyword while
separator (
identifier fahr
operator <
identifier upper
separator )
identifier a
operator =
real 23.00
identifier whileend
Add a comment
Know the answer?
Add Answer to:
write a C++ program that reads in a text file and reads each character or lexemes...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a C program that reads characters from a text file, and recognizes the identifiers in...

    Write a C program that reads characters from a text file, and recognizes the identifiers in the text file. It ignores the rest of the characters. An identifier is a sequence of letters, digits, and underscore characters, where the first character is always a letter or an underscore character. Lower and upper case characters can be part of the identifier. The recognized identifier are copied into the output text. b. Change the C program in exercise 2, so that all...

  • c# csci312: character counter - vector design a program that reads in an ascii text file...

    c# csci312: character counter - vector design a program that reads in an ascii text file (provided) ... Your question has been answered Let us know if you got a helpful answer. Rate this answer Question: C# CSCI312: Character Counter - Vector Design a program that reads in an ASCII text file (provide... C# CSCI312: Character Counter - Vector Design a program that reads in an ASCII text file (provided) and creates an output file that contains each unique ASCII...

  • Write a C++ program that reads text from a file and encrypts the file by adding...

    Write a C++ program that reads text from a file and encrypts the file by adding 6 to the ASCII value of each character. See section 5.11 in Starting out with C++ for information on reading and writing to text files. Your program should: 1. Read the provided plain.txt file one line at a time. Because this file has spaces, use getline (see section 3.8). 2. Change each character of the string by adding 6 to it. 3. Write the...

  • Write a C++ program that reads in a text file and writes the histogram of character counts sorted in alphabetical order to an output file. Eg, if the input file is “to be or not to be”, then the output should be: b **2 e **2 n *1 o ****4

    Write a C++ program that reads in a text file andwrites the histogram of character counts sorted inalphabetical order to an output file. Eg, if theinput file is “to be or not to be”, then the outputshould be:b   **2e   **2n   *1o   ****4r    *1t    ***3

  • In C write a text analyzer program that reads any text file. The program displays a...

    In C write a text analyzer program that reads any text file. The program displays a menu that gives the user the options of counting: • Lines • Words • Characters • Sentences (one or more word ending with a period) • or all of the above Provide a separate function for each option. At the end of the analysis, write an appropriate report.

  • Lab #10 C++ Write a C++ program that reads text from a file and encrypts the...

    Lab #10 C++ Write a C++ program that reads text from a file and encrypts the file by adding an encryption factor (EF) to the ASCII value of each character. The encryption factor is 1 for the first line and increases by 1 for each line up to 4 and then starts over at 1. So, for the 4 th line the EF is 4, for the 5th line it is 1, for the 10th line it is 2. In...

  • Develop a C++ program that reads a paragraph of text from a file. Tokenizes it such...

    Develop a C++ program that reads a paragraph of text from a file. Tokenizes it such that each token is a word, determines whether a token is a palindrome (that is a word that reads the same forward and backward such as ‘madam’ or ‘1991’). Prints all palindrome and the total number of palindrome.Your source code shall consists at least three function apart from main(). Shows a program structure chart,flowchart,source code & output.

  • Write a program that reads in a text file, infile.txt, and prints out all the lines...

    Write a program that reads in a text file, infile.txt, and prints out all the lines in the file to the screen until it encounters a line with fewer than 4 characters. Once it finds a short line (one with fewer than 4 characters), the program stops. For your testing you should create a file named infile.txt. Only upload your Python program, I will create my own infile.txt. Please use a while-loop BUT do not use break, Exit or Quit...

  • Character Count Write a program that reads a file and counts the number of occurrences of...

    Character Count Write a program that reads a file and counts the number of occurrences of each character in the file (case sensitive). The file name is "char.txt". You should use a dictionary to hold the number of occurrences of each character, and print out that dictionary. For example, if the file contains only six characters, "tactic", your dictionary should contain the following key-value pairs (order can be different): {'a': 1, 'c': 2, 'i': 1, 't': 2} Sample Input: Follow...

  • Write a program that opens a text file called input.txt and reads its contents into a...

    Write a program that opens a text file called input.txt and reads its contents into a stack of characters. The program should then pop the characters from the stack and save them in a second text file called output.txt. The order of the characters saved in the second file should be the reverse of their order in the first file. We don’t know the text file length. Input.txt This is a file is for test output.txt tset rof si elif...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT