C++ Create a program: Given a large text file with multiple strings, what would be the most efficient way to read the text file and count how many and which word appears the most words in c++. The text file's size is unknown. I add an image for input .
C++
Create a
Given a large text file with multiple strings, what would be the most efficient way to read the text file and count how many and which word appears the most words in c++.
The text file's size is unknown.
I add an image for input .
NOTE:- The output of the following program may not be as per the given image but the main problem is to sort the words on the basis of their frequency in descending order that has been completed.
you can add the columns of percentage and serial number that is easy part.
Program Plan:-
- Initialize all the required header files.
- Read the file of which the words are to be counted.
- take the map of string and integer.
- count the frequency of each word.
- sort the map on the basis of the value in descending order.
- finally call the print map function to print the values of the map.
The following is the required C++ program-
#include <bits/stdc++.h>
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
//comparing map on the basis of second element
bool compare( const pair <string, int> &a, const pair<string, int> &b)
{
return (a.second < b.second);
}
//the function for printing the map
void PrintMap(vector<pair<string, int>> m)
{
vector<pair<string, int>>::iterator itr;
for ( itr = m.end()-1; itr >= m.begin(); itr--)
cout << itr->first << ": " << itr->second << endl;
}
int main(void)
{
string fileName;
cout<<"Enter the file name\n";
cin>>fileName;
// for storing the words and counting them
map<string, int> cntWord;
{
//Read the file
ifstream file(fileName);
//checking if the file is opened
if (file.is_open())
while (file.good())
{
//storing the word in the local variable
string word;
file >> word;
//look if it is repeated.
if (cntWord.find(word) == cntWord.end())
cntWord[word] = 1;
else //the word is seen before
cntWord[word]++; //increment its count.
}
else
{
cerr << "Couldn't open the file." << endl;
return EXIT_FAILURE;
}
vector<pair<string, int>> vec;
// copy key-value pairs from the map to the vector
map<string, int> :: iterator it2;
for (it2=cntWord.begin(); it2!=cntWord.end(); it2++)
{
vec.push_back(make_pair(it2->first, it2->second));
}
//sorting the map
sort(vec.begin(),vec.end(),compare);
// Print the words map.
PrintMap(vec);
}
return EXIT_SUCCESS;
}
Step by step
Solved in 3 steps with 1 images