Skip to content

Instantly share code, notes, and snippets.

@pileon
Created February 11, 2017 00:03
Show Gist options
  • Save pileon/da7868295e14c0738f7a3c0536acbc35 to your computer and use it in GitHub Desktop.
Save pileon/da7868295e14c0738f7a3c0536acbc35 to your computer and use it in GitHub Desktop.
Simple C++ program to show how to count a specific word in a text file
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <iterator>
int main()
{
std::string filename;
std::cout << "Enter filename: ";
std::cin >> filename;
std::string word_to_search_for;
std::cout << "Enter word to search for: ";
std::cin >> word_to_search_for;
auto tolower = [](std::string& s)
{
std::transform(begin(s), end(s), begin(s), ::tolower);
};
tolower(word_to_search_for);
// Open the file
std::ifstream file_to_read_from(filename);
if (!file_to_read_from)
{
std::cerr << "Could not open file \"" << filename << "\"\n";
return 1;
}
// Now read the file, one word at a time, into a vector
// (Need to do it this way since otherwise we will have the most vexing parse)
std::vector<std::string> all_words = std::vector<std::string>(
std::istream_iterator<std::string>(file_to_read_from),
std::istream_iterator<std::string>());
// Convert all read words into lower-case
std::for_each(begin(all_words), end(all_words), tolower);
// And count all the words matching the one requested
long count = std::count(begin(all_words), end(all_words), word_to_search_for);
std::cout << "The word \"" << word_to_search_for << "\" was found " << count << " times\n";
}
@pileon
Copy link
Author

pileon commented Feb 11, 2017

Needs C++11 since I use lambdas.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment