To provide maximal learning experience, I will not provide pastable code. That's an exercise. You have to do it yourself to learn as much as you can.
This is the perfect scenario for employing a kind of map that creates its value type upon accessing a non-existing key. Fortunately, C++ has such a map in its standard library: std::map<key_type,value_type>
is exactly what you need.
So here's the jigsaw pieces:
- you can read word by word from a stream into a string by using operator
>>
- you can store what you find in a map of words (strings) to occurrences (unsigned number type)
- when you access an entry in the map through a non-existing key, the map will helpfully create a new default-constructed value under that key for you; if the value happens to be a number, default-construction will set it to
0
(zero)
Have fun put this together!