A3/InputProcessor.cpp

67 lines
1.5 KiB
C++
Raw Permalink Normal View History

2024-10-07 02:08:54 -06:00
#include "InputProcessor.h"
#include <fstream>
#include <iostream>
#include <vector>
InputProcessor::InputProcessor() {
_fileIn = std::ifstream();
_allWords = std::vector<std::string>();
2024-10-07 02:08:54 -06:00
}
bool InputProcessor::openStream() {
std::string file;
std::cout << "What is the name of the file you would like to read? ";
std::cin >> file;
if (std::cin.fail()) {
std::cerr << "Invalid file input" << std::endl;
return false;
}
_fileIn.open(file);
if (_fileIn.fail()) {
std::cerr << "Unable to open file, does it exist?" << std::endl;
return false;
}
return true;
2024-10-07 02:08:54 -06:00
}
void InputProcessor::closeStream() { _fileIn.close(); }
void InputProcessor::read() {
2024-10-09 17:20:26 -06:00
// Loop over every character of the file, adding it to the buffer and
// flushing that buffer to _allWords if a separator is found
std::string characterBuffer = "";
char currentChar;
while (_fileIn.get(currentChar)) {
switch (currentChar) {
case ' ':
case '\n':
case '\r':
if (!characterBuffer.empty()) {
_allWords.push_back(characterBuffer);
characterBuffer.clear();
}
break;
default:
// Normalize to uppercase
if (currentChar >= 'a' && currentChar <= 'z') {
currentChar -= 32;
}
characterBuffer += currentChar;
break;
}
}
// Flush the rest of the buffer if the file doesn't end with a space or
// newline
if (!characterBuffer.empty()) {
_allWords.push_back(characterBuffer);
}
2024-10-07 02:08:54 -06:00
}
2024-10-09 17:20:26 -06:00
std::vector<std::string> InputProcessor::getAllWords() const {
return _allWords;
}