Hey everyone I've been having some trouble with this assignment. I need to:
Read each word of the input file. For each word:
- If the word already exists in your word inventory, then simply add 1 to the count. Do not add a duplicate word to your inventory.
- If the word does not exist in your word inventory, add it and set the count to 1.
- After reading all of the input file, close the input file.
- Sort the word inventory by ASCII word order
- Display the word inventory, i.e. list the words and their counts. The output should be sorted in ASCII word order.
My allowed library's are iostream
, iomanip
, string
, cstring
, cerrno
, limits
, sstream
, fstream
, cmath
.
So far, I've been having difficulties with counting the words! My code counts the characters, not the words. My code so far is as follows:
#include "appl.h"
using namespace std;
/*
Class definition file for Appl
*/
string getFileName(ios_base::open_mode parm);
struct wordBlock {
string word;
int count;
};
// Constructor
Appl::Appl()
{
// id string is required for all CS 162 submissions. *** DO NOT CHANGE ***
_cs162_id_ = new string(__FILE__ + string(" compiled ")
+ __DATE__ + string(" ") + __TIME__
+ string(" using g++ ") + to_string(__GNUC__)
+ string(".") + to_string(__GNUC_MINOR__) + string(".")
+ to_string(__GNUC_PATCHLEVEL__));
}
// Destructor
Appl::~Appl()
{
delete _cs162_id_;
}
string inputFileName(ios_base::open_mode parm){
fstream iFile;
string inFileName = "";
int count = 1;
if(parm == ios::in){
while(count != 0){
cout << "Enter an input file name that exists: ";
getline(cin,inFileName);
iFile.open(inFileName.c_str() , ios::in);
if(iFile.good() != true){
cout << "?Invalid file name : file does not exist" <<
count++;
iFile.clear();
}else{
count = 0;
iFile.close();
return inFileName;
}
}
}
}
// Main Routine
int Appl::main(int argc, char ** argv)
{
fstream inFile;
string inFileNames;
inFileNames = inputFileName(ios::in);
inFile.open(inFileNames.c_str(), ios::in);
wordBlock inventory[1000];
if(inFile.is_open()){
for(auto idx = 0; idx < 1000; idx ++){
inventory[idx].word = idx;
inventory[idx].count = 0;
}
while(inFile.peek() != EOF) {
inventory[inFile.get()].count++;
}
for(auto idx = 0; idx < 1000; idx++){
inventory[idx].word = idx;
inventory[idx].count = 0;
}
while(inFile.peek() != EOF) {
inventory[inFile.get()].count++;
}
for(auto idx = 0; idx < 1000; idx++){
if(inventory[idx].count == 0) continue;
cout << "Word " << inventory[idx].word << " occurs " << inventory[idx].count << " times" << endl;
}
inFile.clear();
inFile.close();
}
return 0;
}