### vectors

So I've written this program for counting total number of words in a text file as well as the number of unique words in the file(i.e a word is unique only the first time it is encountered.) So far the total number of words using option t works perfectly but I am having trouble with the unique number of words function mainly the vector declared in it and where exactly to call it in main(). Help will be greatly appreciated, it's due in about 20 hrs. Thanks

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445`` ``````#include #include #include #include using namespace std; int getUniqueWords(std::string s); int main (int argc, char** argv) { enum { total, unique } mode = total; for (int c; (c = getopt(argc, argv, "tu")) != -1;) { switch(c) { case 't': mode = total; break; case 'u': mode = unique; break; } } argc -= optind; argv += optind; std::string word; int count = 0; int counter = 0; while (std::cin >> word) { getUniqueWords(word); count += 1; } switch (mode) { case total: std::cout << "Total: " << count << std::endl; break; case unique: std::cout << "Unique: " << counter << std::endl; break; } } int getUniqueWords(const std::string s) { static std::vector container; std::string word = ""; for(unsigned long i=0; i
You need to step back and think about what you're trying to do. You need to identify the unique words from all the words. So your unique words function is going to need to operate on a collection of all the words.

Currently, your getUniqueWords function takes a single string. One word. So it seems a logical impossibility to identify the number of unique words from all the words if you're only giving the function one single word.

As you read each word in, add it to a vector<string>, using push_back. When you're done reading words in, you will then have all the words in a single vector, ready for you to work on.

Alternatively, you could check to see if a word is already in the vector, and add it only if it isn't, and at the end simply count the number of words in the vector. There are many other ways to do this as well; the issue here is that you need to think in advance about how to do it, and then implement the solution you thought of. That's programming. Thinking and then implementing. Think of your solution first, and then code it.

As an aside, if you were doing this differently, you would add each word to a set<string> as you read them in. std::set removes duplicates for you, so when you had added all the words to the set, you would just ask it what size it was, and that would be the number of unique words.
Last edited on
Yeap that makes a lot of sense. Thanks
Topic archived. No new replies allowed.