Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <filesystem>
- #include <random>
- #include <fstream>
- #include <string>
- #include <list>
- #include <limits>
- #include <boost/program_options.hpp>
- namespace fs = std::filesystem;
- class WordDictionary {
- public:
- WordDictionary() {}
- ~WordDictionary() {
- close();
- }
- bool open(const fs::path& dictionaryPath) noexcept {
- close();
- f.open(dictionaryPath);
- if(!f.is_open())
- return false;
- while(!f.eof()) {
- f.ignore(std::numeric_limits<unsigned int>::max(), '\n');
- mSize++;
- }
- return true;
- }
- void close() noexcept {
- if(f.is_open()) {
- f.close();
- }
- }
- std::string get(unsigned int x) noexcept {
- // After EOF flag is set, stream position will always be -1
- // In that case clear it
- if(f.eof()) {
- f.clear();
- }
- f.seekg(0, f.beg);
- for(unsigned int i = 0; i < x; i++) {
- f.ignore(std::numeric_limits<unsigned int>::max(), '\n');
- }
- std::string word;
- f >> word;
- if(!word.empty()) {
- if(word[word.length() - 1] == '\r') {
- word.erase(word.end() - 1);
- }
- }
- return word;
- }
- // Convinience overload for calling this->get()
- std::string operator[](unsigned int x) noexcept {
- return get(x);
- }
- int size() noexcept {
- return mSize;
- }
- private:
- unsigned int mSize;
- std::ifstream f;
- };
- int main(int argc, char* argv[]) {
- namespace po = boost::program_options;
- po::options_description optDesc("Options");
- optDesc.add_options()
- ("help,h", "Print help message")
- ("dictionary,d", po::value<fs::path>(),"Specify dictionary file")
- ("count,c", po::value<unsigned int>()->default_value(1), "Specify word count (default: 1)")
- ("oneline", "Output all words seperated by spaces in one line");
- po::variables_map optVm;
- po::store(po::parse_command_line(argc,argv, optDesc), optVm);
- po::notify(optVm);
- if(optVm.count("help")) {
- std::cout << optDesc << std::endl;
- return 0;
- }
- if(optVm.count("dictionary") < 0) {
- // stdout (cout) is the output of this program
- // cerr is linked to cout
- // but clog isn't
- std::clog << "No dictionary specified" << std::endl;
- return 1;
- }
- std::random_device randomDevice;
- std::mt19937 randEngine(randomDevice());
- WordDictionary dict;
- unsigned int desiredWordCount = optVm["count"].as<unsigned int>();
- fs::path dictionaryPath = optVm["dictionary"].as<fs::path>();
- bool oneline = false;
- if(optVm.count("oneline")) {
- oneline = true;
- }
- if(!dict.open(dictionaryPath)) {
- std::clog << "Could not open '" << dictionaryPath << '\'' << std::endl;
- return 2;
- }
- std::uniform_int_distribution<unsigned int> randDist(1, dict.size());
- for(unsigned int i = 0; i < desiredWordCount; i++) {
- std::cout << dict[randDist(randEngine)];
- if(oneline) {
- std::cout << ' ';
- } else {
- std::cout << '\n';
- }
- std::cout << std::flush;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement