Answer:
See explaination
Step-by-step explanation:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <sstream>
using namespace std;
// structure to hold the word, frequency and list of lines in which word appears
struct wordFrequency
{
string word;
int frequency;
vector<int> lineNumber;
};
// main method
int main()
{
// input file name. You can change the input file name if your file name is different
string inputFileName = "data.txt";
// creating a map class object to hold words uniquely
map<string, wordFrequency> map_word;
// ifstream class object to open and read from file
ifstream fin(inputFileName);
// validating if file is opened or not
if (!fin.is_open())
{
cout << "Error in opening file!";
exit(1);
}
// string to hold line from file
string line;
// int variable to keep track of line number
int lineNumber = 0;
// fetching lines from file
while (getline(fin, line))
{
// increasing the lineNumber count because we fetch another line
++lineNumber;
// breaking a line into words using stringstream class object
string word;
stringstream iss(line);
// iterating over all the words in a line
while (iss >> word)
{
// if the word is not in the map then we create and add a new pair
auto it = map_word.find(word);
if (it == map_word.end())
{
// creating a new struct object to store new word
wordFrequency w;
w.word = word;
w.frequency = 1;
w.lineNumber.push_back(lineNumber);
map_word.insert({word, w});
}
else
{
// if the word is already there then incresing frequency and push line number into list
it->second.frequency += 1;
it->second.lineNumber.push_back(lineNumber);
}
}
}
// closing the input file
fin.close();
// creating a new output file
ofstream fout("WordFrequency.txt");
if (fout.is_open())
{
// iterating over a map
for (auto word : map_word)
{
// writing data to a output file
fout << "Word is : " << word.second.word << endl;
fout << "Frequency is : " << word.second.frequency << endl;
fout << "Appears in line : ";
for (auto i : word.second.lineNumber)
{
fout << i << " ";
}
fout << endl
<< endl;
}
// closing output file
fout.close();
}
else
{
cout << "Error! Not able to create output file!";
}
}