Done in C++ Step 1. Read a text file and obtain frequencies for all alphabet cha
ID: 3853161 • Letter: D
Question
Done in C++
Step 1. Read a text file and obtain frequencies for all alphabet characters AND spaces. (I believe I have done this correctly, or close to it)
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int letters[27];
int digits[10];
int spaces =0;
for(int i = 0; i < 27; i++) letters[i] = 0;
for(int i = 0; i < 10; i++) digits[i] = 0;
ifstream file;
string filename;
string line;
int length;
cout << "Enter the name of the .txt file to be analyzed : ";
cin >> filename;
cout << endl;
file.open(filename.c_str());
if (file.fail())
{
cout << "Unable to find file " << endl;
file.close();
return 1;
}
while(!file.eof())
{
getline(file, line);
length = line.length();
if (length == 0)
{
spaces++;
}
for(int i = 0; i < length; i++)
{
char c = line.at(i);
if (c >= 65 && c <= 90)
{
letters[c - 65]++;
}
else if (c >= 97 && c <= 122)
{
letters[c - 97]++;
}
else if (c >= 48 && c <= 57)
{
digits[c - 48]++;
}
}
}
file.close();
cout << endl;
for (char c = 'A'; c <= 'Z'; c++)
{
if (letters[c - 65] > 0) cout << c << " : " << letters[c - 65] << endl;
}
for (char c = '0'; c <= '9'; c++)
{
if (digits[c - 48] > 0) cout << c << " : " << digits[c - 48] << endl;
}
return 0;
};
Step 2. Use the frequencies of each letter (and spaces) to build a huffman tree.
I know the concept of building a huffman tree but not how to correctly code it from the generated frequencies.
Step 3. Output each character and the corresponding binary string.
Step 4. Traverse huffman tree and output to a new text file.
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line;
int sum=0;
ifstream inData ;
inData.open("countletters.txt");
while(!inData.eof())
{
getline(inData,line);
int numofChars= line.length();
for (unsigned int n = 0; n<line.length();n++)
{
if (line.at(n) == ' ')
{
numofChars--;
}
}
sum=numofChars+sum;
}
cout << "Number of characters: "<< sum << endl;
return 0 ;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.