Counting the character occurrences in a file
For this task you are asked to write a program that will open a file called “story.txt”
and count the number of occurrences of each letter from the alphabet in this file.
At the end your program will output the following report:
Number of occurrences for the alphabets:
a was used – times.
b was used – times.
c was used – times…. …and so, on
Assume the file contains only lower-case letters and for simplicity just a single
paragraph. Your program should keep a counter associated with each letter of the
alphabet (26 counters) [Hint: Use array]
Your program should also print a histogram of characters count by adding
a new function print Histogram (int counters []). This function receives the
counters from the previous task and instead of printing the number of times each
character was used, prints a histogram of the counters.

Respuesta :

Answer:

hope this helps!

Explanation:

#include <iostream>

#include <fstream>

using namespace std;

void print_histogram(int counter[26])

{

   for(int i = 0; i < 26; ++i){

       cout << (char)(i+97) << " ";

       for(int j = 0; j < counter[i]; ++j){

           cout << (char)254;

       }

       cout << endl;

   }

}

int main()

{

   int counter[26] = {0};

   string filename = "data.txt";

   char byte = 0;

   // opens file in read mode

   ifstream input_file(filename);

   if (!input_file.is_open()) {

       cerr << "Could not open the file - '"

            << filename << "'" << endl;

       return EXIT_FAILURE; // exit if not opened

   }

   // reads every character from the file

   while(input_file.get(byte)){

       if(byte >= 97 && byte <= 122){

           ++counter[byte-97];

       }

   }

   print_histogram(counter); // required print histogram function

   return 0;

}