C++
Part B: (String)
Program Description:
Write a word search program that searches an input data file for a word specified by the user. The program should display the number of times the word appears in the input data file. In addition, the program should count and display the number of grammatical characters in the input data file. Your program must do this by providing the following functions :
void processFile(ifstream &inFile, string wordSearch, int &wordCount, int &grammaticalCount) ; (15%)
void displayResult(string word, int wordCount, int grammaticalCount); (15%)
Both functions should be called from main(). No non-constant global variables should be used. (20%)
Test your program using the file provided “paragraph.dat”.
paragrap.dat
You'll generally read and write longer paragraphs in
academic papers. However, too many long
paragraphs can provide readers with too much information to manage
at one time. Readers
need planned pauses or breaks when reading long complex papers in
order to understand your presented
ideas. Remember this writing mantra: "Give your readers a break!"
or
"Good paragraphs give one pause".
Note: I am assuming that the word is checked for exact match, ie, 'read' will match with 'read' but not 'reader'. Also by grammatical count i am assuming that it stands for the number of characters in the words.
#include <iostream>
#include <string>
#include <fstream> // header file to work with files
using namespace std;
void processFile(ifstream &inFile, string wordSearch, int &wordCount, int &grammaticalCount)
{
string line;
if (inFile.is_open()) // to check if the file is open
{
while (inFile)
{
inFile >> line; // check next word
grammaticalCount += line.length(); // adding the length of the word to the grammatical count
if (line.compare(wordSearch) == 0) // comparing the word to the input word
wordCount++; // if same, then count is increased
}
}
}
void displayResult(string word, int wordCount, int grammaticalCount)
{
cout << word << " appears " << wordCount << " times and the file has " << grammaticalCount << " grammatical count.";
}
int main()
{
ifstream inFile;
string file, wordSearch;
cout << "Enter the name of the file: ";
cin >> file;
cout << "Enter the word to search: ";
cin >> wordSearch;
inFile.open(file); // opening the file
int wordCount = 0, grammaticalCount = 0;
processFile(inFile, wordSearch, wordCount, grammaticalCount); // calculating the counts
displayResult(wordSearch, wordCount, grammaticalCount); // displaying the output
inFile.close(); // closing file
}
Test output:
Enter the name of the file: paragraph.dat
Enter the word to search: one
one appears 2 times and the file has 335 grammatical count.
Get Answers For Free
Most questions answered within 1 hours.