Question

You will write a program that loops until the user selects 0 to exit. In the...

You will write a program that loops until the user selects 0 to exit. In the loop the user interactively selects a menu choice to compress or decompress a file. There are three menu options: Option 0: allows the user to exit the program.

Option 1: allows the user to compress the specified input file and store the result in an output file.

Option 2: allows the user to decompress the specified input file and store the result in an output file.

Assume that the user types any character when prompted to select a menu option. If an input file cannot be opened, the program prints an error message and reprints the menu as shown in the sample solution. The output file is assumed to open correctly. In addition to your main function,

Your solution must include the following non-trivial functions: 1. A function to print out the menu – a void function. Output statements only

2. A function that returns any integer value entered by the user

3. A function to open an input file1 – may want to use as a Boolean value returning function

4. A function to open an output file1

5. A function for compression2

6. A function for decompression2

1These functions require 1 reference parameter – an input file stream or output file stream variable. These functions must be used to open the files. 2These functions require 2 reference parameters – an input and an output file stream variable Example The compression scheme is illustrated below. Decompressed Text Compressed Text Observations abbccc\n 1a2b3c2\n 1a  1 copy of a, 2b  2 copies of b,… \n 4d1\n

2\n  2 copies of \n and so on dddd\n

Note #1: \n represents a newline character

Note #2: You should be able to take a file compressed by your program and use your program to decompress it and recover the original file. In other words, if Option 1 compresses X to produce the file Y, then Option 2 should decompress Y to produce a file Z that is identical to X.

Reminder: Your solution will be tested with several compressed and decompressed files so make sure you test your solution thoroughly before submitting it for grading. Run the sample solution to determine how the program operates.

Your program’s output format should match the output produced by the provided sample solution. You may run the sample solution Project_08_solution by typing the following at a command prompt in a terminal window:

/home/work/cpe211/Executables/Project_08/Project_08_solution Input files are contained in P8_in.zip. Read the README.TXT file included in the zip file

Note: make sure that all necessary inputs are available in the directory that the terminal window is in when the program solution is run (i.e. your ~/CPE211_SUM20/Project_08 directory). Also, run the comparison script before submitting your program to verify your output versus the sample solution output

/home/work/cpe211data/Project_08/CompareSolution.bash Project_08.cpp Summer 2020 CPE211 Project Assignment Project 8 Page 2 of 5

 Global variables are not allowed.

 Using global variables will result in a score of 0 on this assignment.

 You may only use concepts presented in chapters 1-9 of your textbook.

 You must use function prototypes and all function definitions go below main    

The program must have at a minimum the six non-trivial functions listed on page 1.

 The Print Menu Function will have output statements only. It will not read in and return any value

 The function to obtain an integer is to return any integer value. This function will handle the case of invalid character entry only

 The menu selection is to be read into an integer variable – not a character

 No user defined function can call another user defined function except for the obtain integer function which is allowed to call the print menu function

Using your favorite text editor, type your solution and save it as a file named Program_09.cpp within your CPE211_SUM20/Project_08 directory. If there are syntax errors, correct them and compile again. Once your program successfully compiles, run it and verify that the output for your program matches the output from the provided solution executable –

Once you are satisfied with your solution, submit Project_08.cpp via Canvas.

NOTE: make sure that you do not change the order in which the information is entered. An automatic script is used to process all lab submissions, and if the order of the input information is modified, the script will not work properly with your program.

There are 6 obvious tasks that need to be done, and these tasks are written as functions: Print a menu, obtain an integer value, open an input file, open an output file, compress a file and decompress a file

The compression and decompressing technique used in this lab is a very basic idea that lends itself to using loops. In this project, newline characters are included in the compressed file and are considered to be just another character.

Compression algorithm description: The characters in the file to be compressed are read (using the get function) one character at a time. If a character repeats, then the number of times the character is repeated is followed by only one of the characters. Therefore, if a string of 11 P’s (PPPPPPPPPPP) occurs in the input information, the compressed file has the value 11P.

When reading the file for compression, use the get function to read each character because spaces, tabs and new line characters will be read.

Decompression algorithm description: The decompression technique used is easy (For this project, assume the output file contains no errors or missing information) to implement. Read in an integer value (using the extraction operator), then use the get function to read in the character that follows. The character read is written to the output file the number of times specified by the integer value read. For example, 5T is decompressed as TTTTT. Remember you have to read new line characters, so the get function must be used to read the character from the input file. Also, the compressed file will not contain compressed digits since there is no easy way to obtain the number of times the digit occurs (i.e. processing 25 – two number fives and 115 – eleven number fives).

Summer 2020 CPE211 Project Assignment Project

When reading the file for decompression, use the extraction operator for reading the integer value and the get function (so that whitespace characters can be read) to read the character.

close function: This function is used to terminate the association of a file with a file stream variable. someStream.close(): breaks the connection between the file stream variable someStream and the physical file on disk.

clear function: This function is used to take a file stream out of the fail state mode. The use of this function is: someStream.clear(): . To completely reset a file stream variable for use with another file, the file stream variable needs to be closed and cleared. The way to reset a file stream variable (someStream in this handout) is shown below (the order is important):

someStream.close():

someStream.clear():

Open the input file and test the status of the input file stream. If the input file was not successfully opened, print out an error message and abort the option selected – do not loop. If the input file is successfully opened, continue on with opening an output file – assume it opens successfully and performing the selected operation. (Remember to test the sample solution for program operation involving an invalid input file).

Each time a menu selection is made to compress or decompress a file, an input file and an output file must be opened and associated with an appropriate file stream variable.

After each compression or decompression of a file, the input and output file stream variables need to be reset (see the above discussion with the close and clear functions).

Run the provided sample input files to get an idea of how the compression and decompression algorithms for this project works.

Remember that file streams must be reference parameters in a function.

Compressing the file will require loops that keep track of a previous value, and the file to be compressed will have to be read one character at a time.

For printing the menu and menu selection, the program is required to use two functions. Use one function to print the menu and one to obtain an integer value for the selection. Using two functions is easier to follow and code – and it prevents recursive function calls.

PrintMenu(); selection = GetInteger();

// returns any integer value

// process integer value returned – this integer may not be a valid menu choice of 0,1 or 2

The program will be easier to write if the priming read concept is used where the menu is printed and an integer value for the menu selection is obtained before a while loop. Then at the end of the loop, the menu is printed and another selection is obtained. The loop in question is the one that keeps processing user commands until the exit option is selected. Do-While loops work great for this program and do not require a priming read.

Write a function that continually prompts for an integer menu choice until an integer value is entered. Remember that the input stream goes into the fail state for a non-integer character.

An empty input file for compression or decompression results in a message written to the terminal, and the output file will be empty.

For compression, make sure that your program outputs the last compressed character information – Compare your last output with the sample solution. The last number-character pair may not be printed out with some methods

Make sure your program works for the compression input file P8_com_4.txt. This input file has multiple blank lines to end the file. Your program may go into an infinite loop for this input file. To prevent the infinite loop, you need to modify one of your tests to include the status of the input stream as well. For example, you may have in your code:

while (currChar == prevChar)

{

} this needs to become:

while (currChar == prevChar && inputFileStream.good())

where inputFileStream is the name of your input file stream variable.

Compression is harder to program than decompression.

The following algorithms/Functional Decomposition layout should help with writing your program:

Put function prototypes above main

Declare variables in main

Print the menu (Use a function to print out the menu)

Obtain an integer choice (Use a function to obtain an integer)

Loop while the choice is not 0

if the choice is compress or decompress (1 or 2)

Open the input file (use a function)

if file stream is in the fail state mode

print out an error message – cannot open file

else If compression selected

Open the output file (use a function)

Decompress the input file (use a function)

else

Error message for invalid integer entered

Reset the input and output file stream variables using

filestream.close(); filestream.clear()

Print the menu

Obtain integer choice

End of loop

Output program ending message

End of program

Function Definitions go after main

Functions for opening an input or output file, prompt the user for the filename, read the name, echo print it and then open the file. These functions have one reference parameter – the file stream being opened. Write one function for the input file and one for the output file. These functions do not loop on invalid filenames.

Write a function that prints the menu

// Need to be using C++ Program

Homework Answers

Answer #1

Solution provided with given requirement and provided sample output with a text file.

Notes ; implemented functions for showing menu , getting the input choice and compressing & decompressing the files .

However , please note that filenames are read in the Main , which if required can be moved to respective functionalities as well , in which case file handles are not required to be passed to compress & decompress.

################# Code ###################

#include <iostream>
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iomanip>
#include <fstream>

using namespace std;

void showMenu()
{
cout << " Choose from following :\n";
cout << " 1) Compress the file.\n";
cout << " 2) deCompress the file.\n";
cout << " 0) exit \n";
cout << " Enter choice :";

}


int getChoice()
{
bool flag = true ;
string instr ;
int input ;
while (flag) {
      try {
          cin >> instr;
          input = std::stoi(instr);
          if ((input >= 0) & ( input < 3))
              flag = false;
          else
              std::cout << "Invalid input , try again ...\n";
      }
      catch (std::invalid_argument const& e) {
          std::cout << "Invalid Input, try again ... \n";
      }
}
return input ;
}


bool fileReadFile(string flname , ifstream & infile)
{
    infile.open(flname);
    if ( infile.is_open())
      return true;
    else
      return false;

}

bool fileOutFile(string flname , ofstream & outfile)
{
outfile.open(flname);
if( outfile.is_open())
    return true ;
else
    return false;
}

void Compress( ifstream& infile , ofstream& ofile )
{

char curChar ;
char prevChar = '\n';
int cnt = -1 ;
bool prevCharDigit = false ;
int ix = 0 ;
while((infile.get(curChar), infile.eof()) == false)
{
    if ( cnt == -1 )
      prevChar = curChar ;

     if ( !isdigit(curChar ) )
     {

   if ( curChar == prevChar )
   {
          //cout << "11Digit CurChar > " << curChar << " PrevChar > " << prevChar << " PrevDigit " << prevCharDigit << " Cnt :" << cnt << "\n" ;

      cnt++;
   }
   else
      {


        if( ( cnt == 0 ) & prevCharDigit )
          {
       ix = 1;
          } else if ( cnt > 0 )
        {
          ix = 0 ;
          ofile << (cnt+1) ;
          ofile << prevChar ;
          //cout << "Digit CurChar > " << curChar << " PrevChar > " << prevChar << " PrevDigit " << prevCharDigit << " Cnt :" << cnt << "\n" ;

        } else
        {
          if ( ix == 1)
          {
       ofile << ix ;
       ix = 0 ;
          }
           ofile << prevChar ;

        }
        cnt = 0 ;
      }

      prevCharDigit = false;
     } else {
       cnt = 0 ;
       prevCharDigit = true;
       //cout << " Read digit " << curChar ;

       ofile << curChar ;
     }
     prevChar = curChar ;
}
ofile << '\n';
infile.close();
ofile.flush();
ofile.close();

}

void deCompress( ifstream &infile , ofstream & ofile )
{

    char curChar ;
    char prevChar = '\n';
    int cnt = 0 ;
    bool prevCharDigit = false ;
    int ix = 0 ;

    while((infile.get(curChar), infile.eof()) == false)
    {

      if ( isdigit(curChar))
      {
   cnt = cnt*10 + (int) ( curChar - '0') ;
      }
      else
      {
   if ( cnt == 0 )
      ofile << curChar ;
   else
   {
      for ( int i = 0 ; i < cnt ; i++ )
        ofile << curChar ;
   }
   cnt = 0 ;
      }


    }

    infile.close();
    ofile.flush();
    ofile.close();

}

int main()
{

ifstream ifh ;
ofstream ofh ;

string ifilename ;
string ofilename ;

showMenu();
int ichoice = getChoice();


while ( ichoice != 0 )
{

    if ( ichoice == 1 )
    {
      cout << " enter file name to compress : ";
      cin >> ifilename ;
      if (!fileReadFile( ifilename, ifh) )
          cout << "Input file is not valid, try again \n";
      else {
   cout << " enter file name to output compressed file : ";
      cin >> ofilename ;


      if (fileOutFile(ofilename,ofh))
      {
        Compress(ifh,ofh);
      }
      else
        cout << " Output file is not valid \n";
      }
    }

    if ( ichoice == 2 )
    {
      cout << " enter file name to de-compress : ";
      cin >> ifilename ;
      if (!fileReadFile( ifilename, ifh) )
          cout << "Input file is not valid, try again \n";
      else {
   cout << " enter file name to output de-compressed file : ";
      cin >> ofilename ;


      if (fileOutFile(ofilename,ofh))
      {
        deCompress(ifh,ofh);
      }
      else
        cout << " Output file is not valid \n";
      }
    }

    showMenu();
    ichoice = getChoice();
}
}

################ Output #####################

Know the answer?
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
Similar Questions
IN MIPS ASSEMBLY Macro File: Create macros to print an int, print a char, print a...
IN MIPS ASSEMBLY Macro File: Create macros to print an int, print a char, print a string, get a string from the user, open file, close file, read file, and allocate heap memory. You can use more macros than these if you like. Main Program File: Allocate 1024 bytes of dynamic memory and save the pointer to the area. The main program is a loop in which you ask the user for a filename. If they enter nothing for the...
Arrays, loops, functions: Lotto Element Repeated Function Write a function that that takes as parameters an...
Arrays, loops, functions: Lotto Element Repeated Function Write a function that that takes as parameters an array of ints, an int value named element, and an int value named end. Return a bool based on whether the element appears in the array starting from index 0 and up to but not including the end index. Generate Random Array Write a function that takes as parameters an array of integers and another integer for the size of the array. Create a...
(8 marks) Write a program to ask user to input an integer and display the special...
Write a program to ask user to input an integer and display the special pattern accordingly. REQUIREMENTS The user input is always correct (input verification is not required). Your code must use loop statements (for, while or do-while). Your program should use only the following 3 output statements, one of EACH of the followings: System.out.print("-"); // print # System.out.print("+"); // print + System.out.println(); // print a newline Your code must work exactly like the following example (the text in bold...
Write a C program that prompts the user to enter a line of text on the...
Write a C program that prompts the user to enter a line of text on the keyboard then echoes the entire line. The program should continue echoing each line until the user responds to the prompt by not entering any text and hitting the return key. Your program should have two functions, writeStr and readLn, in addition to the main function. The text string itself should be stored in a char array in main. Both functions should operate on NUL-terminated...
Program Behavior Each time your program is run, it will prompt the user to enter the...
Program Behavior Each time your program is run, it will prompt the user to enter the name of an input file to analyze. It will then read and analyze the contents of the input file, then print the results. Here is a sample run of the program. User input is shown in red. Let's analyze some text! Enter file name: sample.txt Number of lines: 21 Number of words: 184 Number of long words: 49 Number of sentences: 14 Number of...
problem 1 Write a program that asks the user for an integer and then prints out...
problem 1 Write a program that asks the user for an integer and then prints out all its factors. For example, when the user enters 84, the program should print 2 2 3 7 Validate the input to make sure that it is not a character or a string using do loop. in c plus plus
This program will output a right triangle based on user specified height triangle_height and symbol triangle_char....
This program will output a right triangle based on user specified height triangle_height and symbol triangle_char. (1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character. (1 pt) (2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have...
Write code in JAVA Write a program that will output a right triangle based on user...
Write code in JAVA Write a program that will output a right triangle based on user specified input height (int) and specified input symbol (char).The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches specified input height. Output a space after each user-specified character, including after the line's last user-specified character. Hint: Use a nested for loop. Ex:If the input...
Description: The purpose of this assignment is to practice writing code that calls functions, and contains...
Description: The purpose of this assignment is to practice writing code that calls functions, and contains loops and branches. You will create a C program that prints a menu and takes user choices as input. The user will make choices regarding different "geometric shapes" that will be printed to the screen. General Comments: Your code must contain at least one of all of the following control types: nested for() loops a while() or a do-while() loop a switch() statement an...
In this lab we will design a menu-based program. The program will allow users to decide...
In this lab we will design a menu-based program. The program will allow users to decide if they want to convert a binary number to base 10 (decimal) or convert a decimal number to base 2 (binary). It should have four functions menu(), reverse(), base2(), and base10(). Each will be outlined in detail below. A rubric will be included at the bottom of this document. Menu() The goal of menu() is to be the function that orchestrates the flow of...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT
Active Questions
  • Consider the following information about the diprotic acid, ascorbic acid. (H2As for short, molar mass 176.1)...
    asked 2 minutes ago
  • You can create an impulse function using the zeros command in MATLAB. impulse=[zeros(1,25) 1 zeros(1,25)] creates...
    asked 2 minutes ago
  • A 400V, 2 pole, 50 Hz, three-phase induction motor is drawing 60 A at 0.85 PF...
    asked 4 minutes ago
  • Net Present Value Method, Present Value Index, and Analysis Donahue Industries Inc. wishes to evaluate three...
    asked 27 minutes ago
  • Analyze what constitutes effective interpersonal communication in personal, professional, and diverse contexts.
    asked 30 minutes ago
  • Use Workbench/Command Line to create the commands that will run the following queries/problem scenarios. Use MySQL...
    asked 33 minutes ago
  • In 2009, the effective income tax rate paid by the top 1% of households in the...
    asked 33 minutes ago
  • 5) Assuming that the following items are stored in a double ended queue called myDeque: 2,...
    asked 35 minutes ago
  • Describe the assumptions behind the economic philosophy regarding the role of the government in the economy...
    asked 39 minutes ago
  • What remains when the reflected intensity is subtracted from the Incident intencity? reflected intensity coefficient transmitted...
    asked 40 minutes ago
  • Consider a computer with a 256 byte address space and a two way 64 byte set...
    asked 43 minutes ago
  • The long-run opportunity cost of government spending that crowds out private investment: a. equals about 10...
    asked 52 minutes ago