"Darren" <fo*****@world.com> wrote in message
news:EA*****************@newsfep3-gui.server.ntli.net...
hi,
i have a file, containing a list of names:
Stuart Byrne
Stuart Byrne
Stuart Byrne
Antony Bradshaw
Antony Bradshaw
Antony Bradshaw
Antony Bradshaw
Antony Bradshaw
Richard Wyville
Richard Wyville
how can i write a program to read the files and add up how many each one
is mentioned?
the names are dynamic (i.e. are not a set list), and the file is recreated
each day.
Many thanks,
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
int main()
{
std::ifstream input("filename");
if(!input)
{
std::cerr << "Cannot open input\n";
return EXIT_FAILURE;
}
std::map<std::string, unsigned int> names;
std::string name;
while(std::getline(input, name))
++(names[name]);
if(!input.eof())
{
std::cerr << "Error reading input\n";
return EXIT_FAILURE;
}
std::map<std::string, unsigned int>::const_iterator it(names.begin());
std::map<std::string, unsigned int>::const_iterator en(names.end());
for( ; it != en; ++it)
std::cout << "The name '" << it->first
<< "' occurs " << it->second << " time"
<< (it->second == 1 ? "" : "s")
<< '\n';
return EXIT_SUCCESS;
}
-Mike