[Solved] Counting list of words in c++ [closed]


In this case there is usually used standard container std::map<std::string, size_t>

For example

#include <iostream>
#include <string>
#include <map>

int main()
{
   std::map<std::string, size_t> m;
   std::string word;

   while ( std::cin >> word ) ++m[word];

   for ( const auto &p : m ) std::cout << p.first << '\t' << p.second << std::endl;
}

You should press either Ctrl + Z (in Windows) or Ctrl + D (in Unix) that to finish the input of words.

Or you could use function std::getline instead of operator >>

For example

#include <iostream>
#include <string>
#include <map>

int main()
{
   std::map<std::string, size_t> m;
   std::string word;

   while ( std::getline( std::cin, word ) && !word.empty() ) ++m[word];

   for ( const auto &p : m ) std::cout << p.first << '\t' << p.second << std::endl;
}

In this case that to finish the input you need to enter an empty string that is to press simply ENTER key.

If the input is

Spain
England
England
France

The output will be

England 2
France  1
Spain   1

2

solved Counting list of words in c++ [closed]