Using C++, and <iostream> if possible, Write a program that can compress a text
ID: 3787693 • Letter: U
Question
Using C++, and <iostream> if possible,
Write a program that can compress a text file consisting of English language alphabet A-zl using run-length encoding scheme. (Weight 50%) Run-Length Encoding The key idea is to replace the repeating character by itself and the number of times that it has been repeated. Consider the following string HELLO WORLD This can be re-written as HEL20 WORLD Notice that since LL was repeated, it was repeated by L2. 2 here indicates that letter L was repeated 2 times. Here's another example: AAAABDGGGADDADGDAD Can be represented as AABDG3AD2ADGDAD You will run the code as follows: To encode $ rle -e -i input.txt -o output. rle And to decode $ rle -d -i output.rle -o output.txtExplanation / Answer
Here is the code for you...
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main()
{
ifstream fin;
string fileName;
string output = "";
cout<<"Enter the name of the file to compress: ";
cin>>fileName;
fin.open(fileName);
int pos = fileName.find(".txt");
fileName = fileName.substr(0, pos);
fileName += "RLE.txt";
ofstream fout;
fout.open(fileName);
char previous, current;
int totalCharCount = 0;
fin>>previous;
totalCharCount++;
int count = 1;
//cout<<"The compressed text is:"<<endl;
while(!fin.eof())
{
fin>>noskipws>>current;
totalCharCount++;
if(fin.eof())
break;
if(tolower(current) == tolower(previous))
count++;
else
{
if(count == 1)
output += previous;
else
{
output += previous;
//output += ('0' + count);
output += to_string(count);
}
count = 1;
previous = current;
}
}
if(count == 1)
output += previous;
else
{
output += previous;
output += ('0' + count);
}
fout<<output<<endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.