unique words using the set function

hi,
part of my assignment needs me to count the unique words from a user input.
This is the code I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <string>
#include <iterator>
#include <set>
#include <iostream>

using namespace std;
int main()

{

string input;
while(getline(cin,input))
{
cout << "the number of unique words" << input.size() << endl;
}
return 0;

}


The code doesnt seem to give out the correct answer,
I using
cat testfile | awk '{for (i=1; i<=NF; i++) x[$i]++} END{print length(x)}'
to check the result but it doesnt match.

Any ideas about what is going wrong??
I guess you ought to be doing what the AWK is doing.

Rather than reading cin with getline, why not use >>?

You also need to use a dictionary to store the counts, indexed works as you've done in the AWK program.
I tried it with cin with >>, but it gives out the same result.

how do I use the dictionary to store the count???
input.size() is telling you how many letters are in the word (if using >>) or line (if using getline()).
Last edited on
I need the number of unique words..... so what should I use???
@Galik

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <iterator>
#include <set>
#include <iostream>

using namespace std;
int main()

{

string input;
getline(cin,input);
cout << "the number of unique words" << input.size() << endl;

return 0;

}


I used getline in the code above but I get the number of letters in the word instead of line as you said, any idea why this is happening??
You need to read each word. So use >> rather than getline().

Also you need to count up how many of each word you have read. So you need to store the words somewhere so you can check if you have read them previously.

Ideally you need to keep a tally of how many times each word was found against the word itself.

HINT:

You can use std::map to associate a number with each word: std::map<std::string, int> words;
Last edited on
OP already included the right header for std::set. A set is an associative container that does not allow duplicates. Therefore, you can add strings to it and it only stores the unique ones. Later, you can see how many there are via std::set.size().

Check out the reference section (click around for examples):
http://cplusplus.com/reference/stl/set/
+1 @moorecm I think I slightly misread the assignment.
Topic archived. No new replies allowed.