Question: Write program using a map with keys and values. Create a program that reads the contents of a text file lists the amount of times
Write program using a map with keys and values. Create a program that reads the contents of a text file lists the amount of times a word appears in the text file. Sample given code is below.
#include
#include
#include
#include
#include
#include
using namespace std;
void split (const string &, char, vector
bool openFile(ifstream &);
bool buildMap(map
void writeIndex(map
string trim(string &);
int main ()
{
map
if (buildMap(wordMap))
{
cout << "The map has " << wordMap.size() << "elements. ";
writeIndex(wordMap);
}
return 0;
}
// The buildMap function opens a file and builds the word map.
bool buildMap(map
{
ifstream inputFile; // The input file
string line; // To hold a line from the file
int lineCount = 0; // To hold the line numbers
vector
// Open the file.
bool status = openFile(inputFile);
// If the file was successfully opened...
if (status)
{
// Get the first line from the file.
getline(inputFile, line);
// While we're not at the end of the file...
while (inputFile)
{
// Update the line counter.
lineCount++;
// Clear previous tokens.
tokens.clear();
// Split the line into tokens.
split(line, ' ', tokens);
// Create elements from the tokens.
for (auto element : tokens)
{
// Create an empty set.
set
// Emplace the new element.
wordMap.emplace(element, mySet);
// Add the current line number to the element's set.
wordMap[element].insert(lineCount);
}
// Get the next line from the file.
getline(inputFile, line);
}
// Close the input file.
inputFile.close();
}
return status;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
