Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program in C++ that read in a text file and outputs another different text file

ID: 3888292 • Letter: P

Question

Program in C++ that read in a text file and outputs another different text file that

The letter/frequency pairs should be given in order of descending frequency. For example, the file should roughly look like this.

```
e, 0.082198
a, 0.050031
(etc)
z, 0.003000

```
I have made up the values in the above table for the sake of example.

It is possible to implement this algorithm in a way that only makes one pass over the corpus. However, if you prefer to read through the file 27 times, that is feasible.

example

test.txt

THEETITLEISONE

outtest.txt

E,4

T,3

H,1

I,2

L,1

S,1

O,1

N,1

Explanation / Answer

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main ()

{

    string str;

    // create a infile variabe to read a file

    ifstream in;

   

    // open the file

    in.open ("test.txt");

   

    // array to store the count of capital and small letters

    int capital[27], small[27],i;

   

    for(i=0;i<27;i++)

    {

        capital[i]=0;

        small[i]=0;

    }

   

    // go through the file

    while(!in.eof())

    {

        // get the complete line in the file

        getline(in,str);

       

        for(i = 0 ; i < str.length() ; i++)

        {

            int temp = (int)str[i];

           

            if(temp >= 65 && temp <= 90)

                capital[temp - 64]++;

            else if(temp >= 97 && temp <= 122)

                small[temp - 96]++;

            else if(str[i] == ' ')

                continue;

            else

            {

                printf("Input should be alphabets! ");

                exit(0);

            }

        }

    }

   

    // close the file

    in.close();

   

    // create an ofstream variable to write into a file

    ofstream out;

   

    // open the file in which you want to write the output

    out.open("outtest.txt");

   

    // write the capital alphabets into the file

    for(i = 1 ; i < 27 ; i++)

        if(capital[i] > 0)

            out<<(char)(i+64)<<" "<<capital[i]<<" ";

           

    // write the small alphabets into the file

    for(i = 1 ; i < 27 ; i++)

        if(small[i] > 0)

            out<<(char)(i+96)<<" "<<small[i]<<" ";

           

    // close the file

    out.close();

   

    return 0;

}

----------------------test.txt------------------------------

THEETITLEISONE

---------------------outtest.txt---------------------------

E 4

H 1

I 2

L 1

N 1

O 1

S 1

T 3

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote