A3/OutputProcessor.cpp

92 lines
2.4 KiB
C++
Raw Normal View History

2024-10-07 02:08:54 -06:00
#include "OutputProcessor.h"
#include <fstream>
#include <iostream>
#include <vector>
OutputProcessor::OutputProcessor() {
_fileOut = std::ofstream();
_allWords = std::vector<std::string>();
_uniqueWords = std::vector<std::string>();
_letterCounts = std::vector<unsigned int>(26, 0);
_wordCounts = std::vector<unsigned int>();
_totalLetterCount = 0;
_totalWordCount = 0;
}
void OutputProcessor::analyzeWords(std::vector<std::string> allWords,
std::string punctuation) {
// Iterate over all words, processing incrementally
for (size_t wordIdx = 0; wordIdx < allWords.size(); wordIdx++) {
std::string& word = allWords.at(wordIdx);
// Remove punctuation from word
size_t punctuationIdx = 0;
while ((punctuationIdx = word.find_first_of(punctuation)) !=
std::string::npos) {
word.erase(punctuationIdx, 1);
}
// Save word internally
_allWords.push_back(word);
// Check all unique words for a match, and if so increment the count
bool foundUnique = false;
for (size_t uniqueWordIdx = 0; uniqueWordIdx < _uniqueWords.size();
uniqueWordIdx++) {
if (_uniqueWords.at(uniqueWordIdx) == word) {
_wordCounts.at(uniqueWordIdx)++;
foundUnique = true;
}
}
// If no unique word exists, add it to both vectors
if (!foundUnique) {
_uniqueWords.push_back(word);
_wordCounts.push_back(1);
}
// Add letter count for each letter in the word
for (size_t letterIdx = 0; letterIdx < word.length(); letterIdx++) {
char letter = word.at(letterIdx);
// Normalize to uppercase
if (letter >= 'a' && letter <= 'z') {
letter -= 32;
}
// Subtracting an uppercase letter by 65 creates its alphabetical
// index
letter -= 65;
_letterCounts.at(letter)++;
}
// Sum total letter count
_totalLetterCount += word.length();
// Increment total word count
_totalWordCount++;
}
}
bool OutputProcessor::openStream() {
std::string file;
std::cout << "What is the name of the file you would like to write to? ";
std::cin >> file;
if (std::cin.fail()) {
std::cout << "Invalid file input";
return false;
}
_fileOut.open(file);
if (_fileOut.fail()) {
std::cout << "Unable to open file, does it exist?" << std::endl;
return false;
}
return true;
}
void OutputProcessor::closeStream() { _fileOut.close(); }
void OutputProcessor::write() {
// TODO
}