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
(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...
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...
(1) Ask the user to input a character. You will draw your right triangle with this...
(1) Ask the user to input a character. You will draw your right triangle with this character. (2) Ask the user to input the number of rows (integer). This will also signify the number of characters at the base of the triangle. (3) Use a nested loop to draw the triangle. The first line will only have one character but will now need to output enough spaces such that the character is output at the end of the row instead...
Write a program in C++ coding that asks the user to input an integer between 25...
Write a program in C++ coding that asks the user to input an integer between 25 and 50, inclusive. Utilize a WHILE loop to test for INVALID input. If the input is INVALID, the loop will repeat, and ask the user to try again. The pseudocode looks like this: Prompt user to input an integer between 25 and 50 Accept the input from the user Test for invalid input (HINT: use a while loop and the OR operator with 2...
Write a program that asks the user to input an integer between 25 and 50, inclusive....
Write a program that asks the user to input an integer between 25 and 50, inclusive. Utilize a WHILE loop to test for INVALID input. If the input is INVALID, the loop will repeat, and ask the user to try again. The pseudocode looks like this: Prompt user to input an integer between 25 and 50 Accept the input from the user Test for invalid input (HINT: use a while loop and the OR operator with 2 relational expressions. You...
Collapse Write a program that prompts the user to input a positive integer. It should then...
Collapse Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. (Note: An even number is prime if it is 2. An odd integer is prime if it is not divisible by any odd integer less than or equal to the square root of the number.) Turn in: Your source code for with The name of your program as a comment at the top...
in c++ Write a C++ program that asks the user to enter an integer number and...
in c++ Write a C++ program that asks the user to enter an integer number and prints it back "vertically" to the screen. Use recursion in your solution. As an example of how the program will work: Please enter an integer: 12345 The integer you entered will print vertically as: 1 2 3 4 5
Part A. Input Validation (Name your C program yourLastName_yourFirstName_Lab4a.c) 1. Place the code you developed in...
Part A. Input Validation (Name your C program yourLastName_yourFirstName_Lab4a.c) 1. Place the code you developed in Lab 2 to obtain a diameter value from the user and compute the volume of a sphere (we assumed that to be the shape of a balloon) in a new program, and implement the following restriction on the user’s input: the user should enter a value for the diameter which is at least 8 inches but not larger than 60 inches. Using an if-else...
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF...
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF A RUNNING COMPILER QUESTION: 1) Fibonacci sequence is a sequence in which every number after the first two is the sum of the two preceding ones. Write a C++ program that takes a number n from user and populate an array with first n Fibonacci numbers. For example: For n=10 Fibonacci Numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 2): Write...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT