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>
usingnamespace 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.
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;
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().