Created
April 25, 2018 06:01
-
-
Save ryanwarsaw/d765333f742aec06f0230138fde4b010 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <vector> | |
#include <sstream> | |
using namespace std; | |
// TODO: Explain how this entire jumble of code works clearly and precisely. | |
vector<string> ParseWords(const string &line) { | |
vector<string> tokens; | |
stringstream stream(line); | |
string token; | |
// Custom predicate to make sure we handle unicode characters properly. | |
std::function<bool(char)> is_alpha_char = [](char character) { | |
return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); | |
}; | |
while (getline(stream, token, ' ')) { | |
// Verify that the string is not empty, and that it contains at least | |
// one alphabetical character (lowercase or uppercase), before adding to list. | |
if (!token.empty() && any_of(begin(token), end(token), is_alpha_char)) { | |
token.erase(remove_if(begin(token), end(token), not1(is_alpha_char)), end(token)); | |
// We check once more to make the string isn't empty, after trimming special characters. | |
if (!token.empty()) tokens.push_back(token); | |
} // else, it's an empty string DoNothing(); | |
} | |
return tokens; | |
} | |
// TODO: Write a comment here about what this code block is doing, and how it works. | |
int main() { | |
string line; | |
int line_number = 1; | |
ifstream infile("../book.txt"); | |
if (infile.is_open()) { | |
while (getline(infile, line)) { | |
vector<string> words = ParseWords(line); | |
cout << line_number << ": " << words.size() << endl; | |
line_number++; | |
} | |
infile.close(); | |
} else cout << "An error occurred when trying to load the specified input file." << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment