Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
#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;
} 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
You can’t perform that action at this time.