Sunday, March 18, 2018

Programming Challenge 17.1 - Unique Words

Example Files: UniqueWords.7z
                           short.txt
                           night.txt

UniqueWords.cpp


#include <algorithm>
#include <cctype>
#include <iostream>
#include <iterator>
#include <fstream>
#include <set>
#include <string>

bool createList(const std::string, std::set<std::string> &);
void printList(const std::set<std::string> &);

int main()
{
    std::string                 filename{};
    std::set<std::string> uniqueWords{};

    std::cout << "UNIQUE WORDS\n\n";
    std::cout << "This program lets you create and display list of unique words\n";
    std::cout << "from a text stored in a file.\n\n";
    std::cout << "Enter the name of the file you wish to open:\n";

    getline(std::cin, filename);

    if (createList(filename, uniqueWords))
    {
        printList(uniqueWords);
        std::cout << "\nThank you for trying this program! Have a nice day!" << std::endl;
    }

    std::cin.ignore();
    return 0;
}

/* **********************************************************
            bool createList() : const string, std::set<string>
    This function reads in words from a file into a set.
   ********************************************************** */

bool createList(const std::string filename, std::set<std::string> &temp)
{
    std::string     word{};
    std::fstream inFile{};
    bool         status{};
   
    inFile.open(filename, std::ios::in);
   
    if (inFile)
    {
        while (inFile >> word)
        {
            transform(word.begin(), word.end(), word.begin(), ::tolower);
            word.erase(remove_if(word.begin(), word.end(), ::ispunct), word.end());

            temp.insert(word);
        }   
        status = true;
    }
    else
    {
        std::cout << "\nFile open error ...\n";
        std::cout << "Please close this program and try again." << std::endl;

        status = false;
    }
    inFile.close();
   
    return status;
}

/* **********************************************************
            printList() : const std::set<string>
    Outputs the list of unique words.
   ********************************************************** */

void printList(const std::set<std::string> &words)
{
    std::cout << "\nUNIQUE WORDS:\n";
    for (auto printWords : words)
    {
        std::cout << printWords << "\n";
    }
}

Example Output:




No comments:

Post a Comment